java - How parse internal array json -
this question has answer here:
i have json:
{ "id": 1, "result": [ { "id": 1, "imgurl": "http://test.com/image.jpg", "title": "image" }, { "id": 2, "imgurl": "http://test.com/image2.jpg", "title": "image2" } ], "jsonrpc": "2.0" }
how can parse internal array, try default retroif gson parsing using model
public class testrequest { public int id; public list<arrayitems> result; public string jsonrpc; } public class item { public int id; public string imgurl; public string title; }
and have error: expected begin_object begin_array. try hand parse
item[] items = gson.fromjson(json, item[].class);
and have error:
expected begin_array begin_object.
what have do?
main problem have list<item>
in pojo , pass item[].class
parser, not match.
item[] items = gson.fromjson(json, item[].class); // ↑ here!!!!
anyway, imho not right way should parse json.
- you have json response main object containing 3 tags (
id
result
,jsonrpc
). - you created java pojos representing main object (
testrequest
)
soooooooo....
use it!
according this, if parse main object have json content.
testrequest data = gson.fromjson(reader, testrequest.class);
now, lets test it, have friendly output, override item::tostring()
in way:
class item { public int id; public string imgurl; public string title; @override public string tostring() { return this.id + "-" + this.title; } }
and tested using main
method:
final string file_path = "c:\\tmp\\38830664.json"; // use own!!! gson gson = new gson(); jsonreader reader = new jsonreader(new filereader(file_path)); testrequest data = gson.fromjson(reader, testrequest.class); (item :data.result) system.out.println(i);
output:
1-image 2-image2
Comments
Post a Comment