1. 通过json字符串给 初始化对象: Gson.fromJson(jsonString string,Class
class Util_JsonToObject{
public static T jsonToObject(String jsonstring, Class type){ // 含泛型的方法 并不是返回值;
Gson son = new Gson();
T t= son.fromJson(jsonstring,type );
return t;
}
}
应用1:
String jsonString = "{'name':'samuel.cai','age':23,'grade':{'course':'English','score':100,'level':'A'}}";
Student student = new JsonStudent();
student = Util_JsonToObject.jsonToObject(jsonString, JsonStudent.class);
class Util_ObjectToJson{
public static String ObjectToJson(Object obj){
Gson json = new Gson();
return json.toJson(obj);
}
}
public class ObjectToJson {
public static void main(String[] args) {
FatherJson.Kids kids = new FatherJson().new Kids("samuel","male",35);
FatherJson father = new FatherJson("蔡xx",69,kids);
String jsonString = Util_ObjectToJson.ObjectToJson(father);
System.out.println(jsonString); //{"name":"蔡xx","age":69,"kids":{"kids_name":"samuel","kids_sex":"male","kids_age":35}}
}
}
//两种创建Jason对象形式:1 key-value; 2 array;
//1.1 创建jason对象;添加属性:如果Key的内容重复 value就会被覆盖;
//1.2 key不能重复;value可以重复;
//1.3 key必须为string, value 5中类型:boolean,数字类型;字符串;字符型,jasonElement类型;
应用3.1 JsonObect创建:
JsonObject.addProperty(key,value)
public class GjsonCreate1 {
public static void main(String[] args) {
JsonObject jobject = new JsonObject();
jobject.addProperty("name1", "水浒传");
jobject.addProperty("name2", "红楼梦");
jobject.addProperty("name3", "三国");
jobject.addProperty("name4", "西游记");
jobject.addProperty("name5", true);
jobject.addProperty("name6", 7);
jobject.addProperty("name7", 'A');
jobject.addProperty("name1", "水浒传~");
System.out.println(jobject.toString());
//{"name1":"水浒传~","name2":"红楼梦","name3":"三国","name4":"西游记","name5":true,"name6":7,"name7":"A"}
}
应用3.2 JsonArray 创建:
JsonArray.add(JsonObject)
public class GjsonCreate2 {
public static void main(String[] args) {
//JsonArray:JSONArray,顾名思义是由JSONObject构成的数组,用 [ { } , { } , ...... , { } ] 来表示
JsonArray array = new JsonArray();
JsonObject sh = new JsonObject();
JsonObject hlm = new JsonObject();
JsonObject sg = new JsonObject();
JsonObject xyj = new JsonObject();
sh.addProperty("宋江", "老大");
hlm.addProperty("贾宝玉","娘娘腔");
sg.addProperty("刘备", "爱哭");
xyj.addProperty("唐僧", "假正经");
array.add(sh);
array.add(hlm);
array.add(sg);
array.add(xyj);
System.out.println(array.toString());
//[{"宋江":"老大"},{"贾宝玉":"娘娘腔"},{"刘备":"爱哭"},{"唐僧":"假正经"}]
jobject.add("名著主人公性格", array);// jobject引用的是3.1 中的对象
System.out.println(jobject.toString());
//{"name1":"水浒传~","name2":"红楼梦","name3":"三国","name4":"西游记","name5":true,"name6":7,"name7":"A","名著主人公性格":[{"宋江":"老大"},{"贾宝玉":"娘娘腔"},{"刘备":"爱哭"},{"唐僧":"假正经"}]}
}