Gson is required to return Java jsonarray
•
Java
I can't return jsonarray, but my object seems to be a string The value of myArray is the same as that of jsonstring The object is a string object, not a jsonarray And jsonstring and myArray PRNT:
[{"id":"100002930603211","name":"Aardvark Jingleheimer","picture":"shortenedExample.jpg" },{"id":"537815695","name":"Aarn Mc","picture":"shortendExample.jpg" },{"id":"658471072","name":"Adrna opescu","picture":"shortenedExample.jpg" }]
How to convert it to an actual Java jsonarray? thank you!
//arrPersons is an ArrayList Gson gson = new Gson(); String jsonString = gson.toJson(arrPersons); JsonParser parser = new JsonParser(); JsonElement myElement = parser.parse(jsonString); JsonArray myArray = myElement.getAsJsonArray();
Solution
I think you can do what you want without writing out the JSON string and Rereading It:
List<Person> arrPersons = new ArrayList<Person>(); // populate your list Gson gson = new Gson(); JsonElement element = gson.toJsonTree(arrPersons,new TypeToken<List<Person>>() {}.getType()); if (! element.isJsonArray()) { // fail appropriately throw new SomeException(); } JsonArray jsonArray = element.getAsJsonArray();
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
二维码