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?
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);
Related
Is is mandatory to use TypeToken (as recommended in the Gson doc) as type when converting a list into json like below -
new Gson().toJson(dateRange, new TypeToken<List<String>>() {}.getType());
For me below code is also working -
new Gson().toJson(dateRange, List.class);
Just want to make sure that code doesn't break.
As per docs -
If the object that your are serializing/deserializing is a
ParameterizedType (i.e. contains at least one type parameter and may
be an array) then you must use the toJson(Object, Type) or
fromJson(String, Type) method. Here is an example for serializing and
deserializing a ParameterizedType:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
This is the special case, in other cases you can use class type directly.
For reference - http://google.github.io/gson/apidocs/com/google/gson/Gson.html
Hope this helps
This may to possible of duplicate i need to convert the list to jsonobject like this
{"EmailID":"Djlj#sl.com","PhoneNumber":"870796850","ID":2}
like this how can i achieve this so far what i have tried is :
List<CustomerModel> listobj=new ArrayList<CustomerModel>();
listobj=timetrackerdaoobj.Listtoserver();
String gsonString=new Gson().toJson(listobj, collectionType);
In this method am getting jsonarray like this
[{"EmailID":"Djlj#sl.com","PhoneNumber":"870796850","ID":2}]
But i need format like this:
{"EmailID":"Djlj#sl.com","PhoneNumber":"870796850","ID":2}
Try this way,
String gsonString=new Gson().toJson(listobj, collectionType);
gsonString = gsonString.replace("[","").replace("]","");
System.out.println(gsonString); // here you got expected answer
this may helps you.
You want a JSON Object, and not a JSON Array. So pass only your java object and not the list into your Gson converter :
String gsonString = new Gson().toJson(listobj.get(0), yourType);
Can anyone explain me how to correctly insert a subobject into JSONObject? I've tried both implementations - org.json.simple and org.json and code like:
JSONObject obj = new JSONObject();
obj.put("key", "value");
obj.put("subobject", obj.toString());
After these strings I except:
{"key":"value","subobject":{"key":"value"}}
But actual value is:
{\"key\":\"value\","subobject":{"key":"value"}}
It always escapes the quotes while inserting JSONObject so I can't do it correctly. Of course I can try to modify the code but I wonder - really, nobody asked that before? So I guess the solution is right in front of me but I can't just see it. Help me please.
Simply put
JSONObject obj = new JSONObject();
JSONObject subobj = new JSONObject();
obj.put("key", "value");
obj.put("subobject", subobj);
without the toString()
Also, the way you print the JSONObject affects how it is displayed. Do you use System.out? or the debugger? As long as you can parse the result string again into a JSONObject, there is no real problem, right?
There is json in my metod. I want json change to object bean. compiler warns and asks to remove generic.
This example does not work:
Gson gson = new Gson();
List<MyBean> myBean = gson.fromJson(
result.getBody(), List<myBean>.class);
So does run, but I can not get to the bean:
Gson gson = new Gson();
List<MyBean> myBean = gson.fromJson(
result.getBody(), List.class);
MyBean.get(0).getFirstName();
error java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to com.home.bean.MyBean
How do I solve this problem?
Try this:
Type myBeanListType = new TypeToken<ArrayList<MyBean>>() {}.getType();
List<MyBean> mappedList = new Gson().fromJson(result.getBody(), myBeanListType );
Your code would have to be changed to:
List<MyBean> myBean = gson.fromJson(result.getBody(), new TypeToken<List<MyBean>>() {}.getType());
Per the Gson user guide here, (under Serializing and Deserializing Generic Types section):
When you call toJson(obj), Gson calls obj.getClass() to get
information on the fields to serialize. Similarly, you can typically
pass MyClass.class object in the fromJson(json, MyClass.class) method.
This works fine if the object is a non-generic type. However, if the
object is of a generic type, then the Generic type information is lost
because of Java Type Erasure.
You can solve this problem by specifying the correct parameterized
type for your generic type. You can do this by using the TypeToken
class.
Hence, you would have to use TypeToken when dealing with generics.
I have JSON like this:
{"foos":[{"id":1}, {"id":2}]}
I can turn it into List<Foo> pretty simply with GSON, like this:
Type t = new TypeToken<List<Foo>>(){}.getType();
JsonObject resp = new Gson().fromJson(
new JsonParser().parse(json).getAsJsonObject().get("foos",t);
But let's assume that I also have another JSON, where the name of the array and type changes
{"bars":[{"id":3},{"id":9}]}
Of course I could just swap the "foos" parameter for "bars", but if it's possible, I'd like my software to do it for me.
Is there a way to extract the name of the array child with the GSON library?
I'm not sure if I understood what you want correctly, but aren't you referring to the use of generics? I mean you could write a method that returns you a List of your relevant class? Something along the lines of
Type type = new TypeToken<List<MyClass>>() {}.getType();
List<MyClass> myObjects = getMyObjects(new JsonParser().parse(json).getAsJsonObject().get("foos"), type);
public static List<T> getMyObjects(String jsonString, Type type) {
Gson gson = new Gson();
List<T> myList = gson.fromJson(jsonString, type);
return myList;
}
Looking at your JSON examples, I assume that the name of the list element can change, but not the content of the list. If this is correct, you could parse your JSON response just like this:
Type mapType = new TypeToken<Map<String, List<Foo>>>() {}.getType();
Map<String, List<Foo>> map = gson.fromJson(jsonString, mapType);
And then you can access the name of the list with:
String listName = map.keySet().iterator().next();
If the content of the list could also change, things get a bit more complicated...