In my Android project I'm trying to convert a received JSONArray to a List. With the help of this SO answer I got a bit further. I now have the following code:
Gson gson = new Gson(); JSONArray jsonArray = NetworkUtilities.getData("mymodeldata"); Type listType = new TypeToken<List<MyModel>>(){}.getType(); List<MyModel> myModelList = gson.fromJson(jsonArray, listType);
Unfortunately it complaints at the last line that the method fromJson(String, Type) in the type Gson is not applicable for the arguments (JSONArray, Type). I don't really know how to solve this.
Does anybody know how I can solve this?
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
Java For TestersWe can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument.
You can easy get a JSON array element by key like this: var value = ArrName['key_1']; //<- ArrName is the name of your array console. log(value);
If you see the answer there, you can notice that the first parameter in the fromJson()
method was a String
(the json object). Try to use the toString()
on the JsonArray like this:-
List<MyModel> myModelList = gson.fromJson(jsonArray.toString(), listType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With