GSON使用記録

1439 ワード

需要
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.空の文字列に遭遇した場合、変換タイプが間違っています.
プロセス