Simplest Gson.fromJson example fails - android

Given the following code:
final class retVal { int photo_id; }
Gson gson = new Gson();
retVal ret = gson.fromJson("{\"photo_id\":\"383\"}", retVal.class);
I get ret set to null.
I'm sure I've missed something obvious out, as toJson with a class also fails, although hand-construction through JsonObject works.

Declare your class retVal outside the method.

Gson helps you to serialize objects. So, you need an object first. Based on your approach, you want to do something like
RetVal myRetVal = new RetVal();
Gson gson = new Gson();
String gsonString = gson.toJson(myRetVal);
To retrieve the object back from the string:
Gson gson = new Gson();
RetVal myNewRetValObj = gson.fromJson(gsonString, RetVal.class);

Related

How do I read JSON as String with Gson?

I'm getting a Json from a WebService and I want to print it as a String in my LogCat. I've tried the following:
Gson gson = new Gson();
HttpEntity getResponseEntity = httpResponse.getEntity();
InputStream is = getResponseEntity.getContent();
Reader reader = new InputStreamReader(is);
Type snsType = new TypeToken<SNSRegister>(){}.getType();
snsRegister = gson.fromJson(reader, snsType);
String jsonString = convertStreamToString(is);
snsRegister is an instance of my serializable class, i'm trying to print the JSON in my logcat by converting the InputStream object to String with the convertStreamtoString method:
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
but my String is always empty and I don't know why. snsRegister is not null, so that isn't the problem.
If this is really important for you to do, Gson can take a String.
I don't recommend reading the Stream twice, though you can do it with mark() and reset(). Since Gson will deserialize a String in addition to Reader, so you can just pass the String into Gson like this:
HttpEntity getResponseEntity = httpResponse.getEntity();
InputStream is = getResponseEntity.getContent();
String jsonString = convertStreamToString(is);
Log.i("MyTAG", jsonString);
Gson gson = new Gson();
Type snsType = new TypeToken<SNSRegister>() {}.getType();
snsRegister = gson.fromJson(jsonString, snsType);
I don't recommend doing this in production though, as the conversion to a String is a lot of extra work. But you can use this temporarily for debugging, obviously; the way you're currently doing it is the best way for production.
Another option would be to convert the SNSRegister object back to JSON with gson.toJson(), but that would be even slower.
Most probably your stream has been read once by GSON.
If you really, really want to read it twice you need to reset() a stream but first you have to mark() the position you want to reset to.
But all you want is to print your JSON in logcat just add toString() method to your SNSRegister class or even better user Retrofit logging mechanism.

GSON sends my object as a string not a object

I am using Volley with GSON and I need to send a object as a parameter to my call.
This is how I do the object:
JSONObject params = new JSONObject();
Gson gson = new Gson();
String json = gson.toJson(route);
params.put("route", json);
And then I call my Volley JsonObjectRequest function.
The problem is that the params look like this:
{"route":"{\"bounds\":{\"northeast\":{\"lat\":52.3777194,\"lng\":4.924666999999999},\"southwest\":{\"lat\":52.36881109999999,\"lng\":4.9011479}},\"copyrights\":\"Map data ©2014 Google\", etc...}"
As you can see, instead of sending it as a object, its sending it as a String , and that's why I get the " before the {} (before the object begins). The params should look like:
{"route":{\"bounds\":{\"northeast\":{\"lat\":52.3777194,\"lng\":4.924666999999999},\"southwest\":{\"lat\":52.36881109999999,\"lng\":4.9011479}},\"copyrights\":\"Map data ©2014 Google\", etc...}
So no " before { like this:
{"route":{myObject}
What an I doing wrong here?
You don't want to mix JSONObject and GSON.
That's 2 different libraries.
Use gson.toJsonTree to obtain an element, then use JsonObject instead of JSONObject:
JsonObject params = new JsonObject();
Gson gson = new Gson();
params.add("route", gson.toJsonTree(route));

Deserializing Json in Android

In my backend I have a class User which has multiple Trips.
Those trips have multiple user.
This is a circular reference.
I use this code in my rest service to serialize the user object:
Gson gson = new Gson();
return gson.toJson(user, TripUser.class);
In my android app I do the following:
Gson gson = new Gson();
TripUser Tuser = gson.fromJson(data, TripUser.class);
return Tuser;
What can I do about the circular reference exception?
Is there another way to make this work?
You should try to use flexjson 2.1
This would solve your problem because you can chose which items he should serialize to Json etc.
Also this library gives no problems with circular references
I am not fully sure , but u can try like this :
Gson gson = new Gson();
Type type = new TypeToken<TripUser>(){}.getType();
TripUser user = (TripUser) gson.fromJson(data, type);

How do I convert a JSONObject to class object?

I need to convert a JSONObject to a Location object using gson libraries for an android project of mine. I'm not sure on how to do this. Can anyone help me with this. Thanks in advance.
I have a code something like
JSONArray input = new JSONArray(extras.getString("loc_json"));
I wanted to convert the JSONObject taken from the JSONArray to a Location class object. I just wanted to know whether there is a function that does it directly.
Pardon me if I framed the question in a wrong way. Since I haven't got the direct function, I did it in this way.
loc_temp = (Location) gson.fromJson(input.getJSONObject(i).toString(), Location.class);;
Sorry for the stupid question.
Here's a tutorial for GSON - I think it should help bolster your understanding. Essentially the parsing is done like this:
String mJsonString = "...";
JsonParser parser = new JsonParser();
JsonElement mJson = parser.parse(mJsonString);
Gson gson = new Gson();
MyDataObject object = gson.fromJson(mJson, MyDataObject.class);
if you still want to use org.json.JSONObject:
org.json.JSONObject o;
ObjectMapper m = new ObjectMapper();
MyClass myClass = m.readValue(o.toString(), MyClass.class);
use com.google.gson.JsonObject & JsonArray instead of org.json.*
like this :
Gson gson = new Gson();
Type typeOfT = new TypeToken<List<Location.class>>(){}.getType();
JsonParser parser = new JsonParser();
JsonObject jo = (JsonObject) parser.parse(jsonStr);
JsonArray ja = jo.getAsJsonArray("memberName");
list = gson.fromJson(ja, typeOfT);
Convert JSONObject to Model class::
val jsonObject = JSONObject(data[0].toString())
val jsonModel = jsonObject.getJSONObject(KEY.message).toString()
val chatModel = Gson().fromJson(model, ChatModel::class.java))
For kotlin
val objType = object : TypeToken<MyClass>() {
}.getType()
var myclassObj = gson.fromJson(value,objType)
or
val objectResponse = Gson().fromJson(Gson().toJson(resp), MyClass::class.java)

How change rules for Gson parser?

I want to change rules for Gson parser (json parser wrote by google for Android). For example I have the object of class:
enum Type
{
PRIMARY,
SECONDARY
}
class A
{
public int i = 4;
public Type type = Type.PRIMARY;
}
A a = new A();
Now if I will convert that object via Gson converter:
Gson gson = new Gson();
JsonElement json = gson.toJson(a);
I will get that json element: {"i":4,"type":"PRIMARY"}. Instead of this I want to get: {"i":4,"type":0}, i.e. ordinal of type instead of a name of it.
How can I do that?
Tnx.
Ok, I found the answer:
For doing that need to create Gson object from GsonBuilder. But before that register a new type hierarchy adapter for gson builder for Enum.class type with your own json serializer that will do the work.
// new Json serializer for Enum<?> class
class ObjectTypeSerializer implements JsonSerializer<Enum<?>>
{
private static final JsonParser mParser = new JsonParser();
public JsonElement serialize(Enum<?> object_,
Type type_,
JsonSerializationContext context_)
{
// that will convert enum object to its ordinal value and convert it to json element
return mParser.parse(((Integer)object_.ordinal()).toString());
}
}
// creation of gson builder
GsonBuilder gsonBuilder = new GsonBuilder();
// registration of type hierarchy adapter
gsonBuilder.registerTypeHierarchyAdapter(Enum.class, new ObjectTypeSerializer());
// creation gson from builder
Gson gson = gsonBuilder.create();
Now gson will do the work!

Categories

Resources