GSON使用记录

需求

gson是常用的框架

分析

1.如何解析数组

[
  {
    "id": "1",
    "tag": "tag1",
    "tobe": "tobe1"
  },
  {
    "id": "2",
    "tag": "tag2",
    "tobe": "tobe2"
  }
]
Gson gson = new Gson();
Course[] courses = gson.fromJson(sg.toString(), Course[].class);

2.带数据头的数组数据

{
  "code":"1",
  "msg":"success",
  "data":[
    { "id": "1",
      "info": "1连",
      "parent_id":"0",
      "tobe": "tobe1"
    },
    { "id": "2",
      "info": "2连",
      "parent_id":"1",
      "tobe": "tobe1"
    },
    { "id": "3",
      "info": "3连",
      "parent_id":"2",
      "tobe": "tobe1"
    }
  ]
}

public class DataHead {

    public int code;

    public String msg;

   @SerializedName(value = "datas",alternate = {"data","dataa"})
    public T[] datas;
}

Gson gson = new Gson();
Type unitType = new TypeToken>(){}.getType();
DataHead head = gson.fromJson(str,unitType);
return head.datas;

3.jsonReader使用

4.遇到空字符串时如果转换类型会报错的

过程

你可能感兴趣的:(GSON使用记录)