yigeng 2017-07-12
json在线翻译工具:
http://www.bejson.com/jsoneditoronline/
第一种:
首先要下载所需的函数库,我这里使用的是google-gson-2.2.4,(下载链接:http://download.csdn.net/detail/a771948524/6668573)。下载完成之后,在项目上新建一个lib文件,把下载文件复制进去,右键选择添加至构建路径。至此,准备工作基本完成。
接下来就是写代码了。这里,我把代码贴出来,如下所示:
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* @date 2015-05-25
* @author jack
*
*/
public class CreateJson {
public static void main(String[] args) {
//新建json对象就可以直接增加属性了
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("cat", "it");
//建立json数组,数组里面是一组或多组json对象的数据
JsonArray jsonArray = new JsonArray();
JsonObject jObject1 = new JsonObject();
jObject1.addProperty("id", 1);
jObject1.addProperty("name", "java");
jObject1.addProperty("ide", "Eclipse");
jsonArray.add(jObject1);
JsonObject jObject2 = new JsonObject();
jObject2.addProperty("id", 2);
jObject2.addProperty("name", "Swift");
jObject2.addProperty("ide", "X-code");
jsonArray.add(jObject2);
JsonObject jObject3 = new JsonObject();
jObject3.addProperty("id", 3);
jObject3.addProperty("name", "C#");
jObject3.addProperty("ide", "Visual Studio");
jsonArray.add(jObject3);
jsonObject.add("languages", jsonArray);
jsonObject.addProperty("pop", "true");
System.out.println(jsonObject.toString());
}
} import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* @date 2015-05-25
* @author jack
*
*/
public class CreateJson {
public static void main(String[] args) {
//新建json对象就可以直接增加属性了
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("cat", "it");
//建立json数组,数组里面是一组或多组json对象的数据
JsonArray jsonArray = new JsonArray();
JsonObject jObject1 = new JsonObject();
jObject1.addProperty("id", 1);
jObject1.addProperty("name", "java");
jObject1.addProperty("ide", "Eclipse");
jsonArray.add(jObject1);
JsonObject jObject2 = new JsonObject();
jObject2.addProperty("id", 2);
jObject2.addProperty("name", "Swift");
jObject2.addProperty("ide", "X-code");
jsonArray.add(jObject2);
JsonObject jObject3 = new JsonObject();
jObject3.addProperty("id", 3);
jObject3.addProperty("name", "C#");
jObject3.addProperty("ide", "Visual Studio");
jsonArray.add(jObject3);
jsonObject.add("languages", jsonArray);
jsonObject.addProperty("pop", "true");
System.out.println(jsonObject.toString());
}
}第二种:
第三种:
Jackson 是一个 Java 用来处理 JSON 格式数据的类库,性能非常好。
示例:
{
: { : , : },
: ,
: ,
:
} class User {
Gender { MALE, FEMALE };
class Name {
_first, _last;
getFirst() { _first; }
getLast() { _last; }
void setFirst( s) { _first = s; }
void setLast( s) { _last = s; }
}
Gender _gender;
Name _name;
_isVerified;
[] _userImage;
Name getName() { _name; }
isVerified() { _isVerified; }
Gender getGender() { _gender; }
[] getUserImage() { _userImage; }
void setName(Name n) { _name = n; }
void setVerified( b) { _isVerified = b; }
void setGender(Gender g) { _gender = g; }
void setUserImage([] b) { _userImage = b; }
}ObjectMapper mapper = ObjectMapper(); User user = mapper.readValue( File(), User.class);