Java – how to deserialize JSON arrays using gson
•
Java
I want to use gson to deserialize a JSON array I tried to do it, but I couldn't
JSON array:
[ {"ID":1,"Title":"Lion","Description":"bla bla","ImageURL":"http:\/\/localhost\/lion.jpg"},{"ID":1,"Title":"Tiger","ImageURL":"http:\/\/localhost\/tiger.jpg"} ]
I get JSON arrays from PHP scripts:
$array = array ( array ( 'ID' => 1,'Title' => 'Lion','Description' => 'bla bla','ImageURL' => 'http:\/\/localhost\/lion.jpg' ),array ( 'ID' => 2,'Title' => 'Tiger','ImageURL' => 'http:\/\/localhost\/tiger.jpg' ),); echo json_encode ($array);
Solution
To deserialize jsonarray, you need to use typetoken You can read more information from the gson user guide Example code:
@Test public void JSON() { Gson gson = new Gson(); Type listType = new TypeToken<List<MyObject>>(){}.getType(); // In this test code i just shove the JSON here as string. List<Asd> asd = gson.fromJson("[{'name':\"test1\"},{'name':\"test2\"}]",listType); }
If you have a jsonarray, you can use it
... JSONArray jsonArray = ... gson.fromJson(jsonArray.toString(),listType); ...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码