JSON解析和GSON解析

来源:互联网 发布:java redis isinmulti 编辑:程序博客网 时间:2024/06/08 10:13

一个json对象


{“name”:”sam”,”age”:18,”weight”:60}

/**JSON/JSONObject jsonObj = new JSONObject(json1);String name = jsonObj.optString("name");int age = jsonObj.optInt("age");int weight = jsonObj.optInt("weight");/**GSON/首先我们需要一个实体类public class People{    public String name;    public int mAge;       public int weight;}然后就可以解析了Gson gson = new Gson();Poeple people = gson.fromJson(json1, People.class);

一个数字数组


[12,13,15]

 /**JSON/      JSONArray jsonArray = new JSONArray(json2);    for(int= 0; i < jsonArray.length();i++) {        int age = jsonArray.optInt(i);    } /**GSON/         //解析成int数组    Gson gson = new Gson();    int[] ages = gson.fromJson(json2, int[].class);    //解析成IntegerList。    Gson gson = newGson();    List<Integer> ages = gson.fromJson(json2, new    TypeToken<List<Integer>>(){}.getType);

json array中有object


[{“name”:”sam”,”age”:18},{“name”:”leo”,”age”:19},{“name”:”sky”, “age”:20}]

 /**JSON/      JSONArray jsonArray = new JSONArray(json3);    for(int= 0; i < jsonArray.length();i++) {        JSONObject jsonObject = sonArray.optJSONObject(i);        String name = jsonObject.optString("name");        int age = jsonObject.optInt("age");    } /**GSON/    //解析成List。    Gson gson = new Gson();    List<People> peoples = gson.fromJson(json3, new    TypeToke<List<People>>(){}.getType);
0 0