Michael Hubbard
Michael Hubbard

Reputation: 81

Gson fromJson returning empty JsonObject

So, I've got a String that is the result of a toJson method I've implemented on a class, and have confirmed in my test code that it is the correct Json representation of my class. My goal is to turn this String into a JsonObject and pass it to a constructor, using Gson. However, I'm running into an odd problem.

This is the code I'm calling:

Gson gson = new Gson();
JsonObject jObj = gson.fromJson(jsonString, JsonObject.class);

I have used literally this exact same snippet of code before in many places in my project, for other classes, and it has worked fine. I even copied one of those functional snippets of code into this test class and tried it. However, every version I try results in the same thing--jObj is an empty set of brackets.

I don't understand how it's happening. I've confirmed that jsonString has all the fields it should need. Why is Gson returning an empty JsonObject? No exceptions are being thrown.

Upvotes: 3

Views: 7056

Answers (4)

Larkin Crain
Larkin Crain

Reputation: 1

I had this issue as well.

I was using

return gson.fromJson(response, JsonObject::class.java)

And I was receiving an object with only the default values populated.

I had to explicitly define the serialized names for each property in my JsonObject class that was different from how it was named in the json response.

For example, if in the json I was parsing the field name was "total_score', but my JsonObject had a field named "totalProperty", I had to use the @SerialedName annotation to define the relationship.

@SerializedName("total_score")
val TotalScore : Int = 0

Upvotes: 0

Zachary Loughridge
Zachary Loughridge

Reputation: 177

Ok so i know this is a little old but I had the same exact issue. The resolution was changing the jar file. I had a similar code sample working in another project but then I was experiencing the exact same problem in another. Well the problem was an older gson-2.1.jar. Updated the problem application to the matching gson-2.3.1.jar and all was working. Hope this helps.

Upvotes: 5

Irshu
Irshu

Reputation: 8436

For my case, I was accidentally using the following initializer in my dagger module.

Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create()

I removed the setFieldNamingPolicy and it worked.

Upvotes: 0

Chthonic Project
Chthonic Project

Reputation: 8336

From your comment that says the string is {"varName":1, "otherVarName":2, "thirdVarName":3.4}, looks like the serialized object was a Map. You may need to specify the type token:

gson.fromJson(jsonString, new TypeToken<Map<K,V>>() {}.getType());

where K and V are the key and value types of the map. If it is not a Map, specify whatever class the jsonString was obtained from.

Upvotes: 0

Related Questions