3

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.

  • 3
    What is the contents of jsonString when you get empty JsonObject? – Wand Maker Jul 22 '15 at 19:38
  • the string is "{"varName":1, "otherVarName":2, "thirdVarName":3.4}" and so on. Typical Json Object – Michael Hubbard Jul 22 '15 at 19:41
  • 1
    It's working for me I got the expected output. Please show a small program demonstrating the problem. – Alexis C. Jul 22 '15 at 19:43
  • 1
    What if you add `if (jsonString.trim().isEmpty()) throw new IllegalArgumentException();` ? – Dici Jul 22 '15 at 19:43
  • It doesn't throw the IllegalArgument exception if I add that code. The string isn't empty at any point--just the JsonObject that gets returned. Not null, but empty. – Michael Hubbard Jul 22 '15 at 19:47
  • As for a small program demonstrating the problem, that's what I'm trying to figure out--it works for me too, everywhere but this one particularly test case. I now suspect that the issue may somehow lie in where in my project directory structure the test is--but I have trouble understanding how. The problem isn't in a reference to any of the other classes in question, it's happening entirely within Gson.fromJson(). – Michael Hubbard Jul 22 '15 at 19:48
  • It's hard to help you as we cannot reproduce the problem... Is the parser strict or tolerant? Maybe the string contains some weird non-printable characters. – Alexis C. Jul 22 '15 at 20:04
  • All of the fields are plaintext characters, with either integer, boolean, or double values. No weird characters that I can see. More to the point, copying code from another part of my project that did work elsewhere no longer works here. Is there anything in Gson that could be affected just from being instantiated inside a different directory? – Michael Hubbard Jul 22 '15 at 20:08
  • @MichaelHubbard does this part of the project have the same classpath as the places where your code works ? How do you build the project ? If you can do it, visualize your dependencies. – Dici Jul 22 '15 at 20:11

4 Answers4

5

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.

0

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.

Chthonic Project
  • 8,216
  • 1
  • 43
  • 92
  • @Chthonic Project - I believe you're absolutely correct. To elaborate: https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Generic-Types – paulsm4 Jul 22 '15 at 19:47
  • @MichaelHubbard : added explanation, and the link posted by paulsm4 explains this in detail. – Chthonic Project Jul 22 '15 at 19:49
  • But the OP is trying to get a `JsonObject` from this `String`, not a `Map`. – Alexis C. Jul 22 '15 at 19:49
  • @AlexisC. : As far as I can see, OP has a string that is most probably obtained from a `Map`. – Chthonic Project Jul 22 '15 at 19:51
  • Yes but as I understand, the issue is the conversion `String -> JsonObject`. This `String` could also come from any other class, not necessarily a `Map`. – Alexis C. Jul 22 '15 at 19:52
  • The String does not come from a Map. It comes from calling Gson.toJson on an Object somewhere else. – Michael Hubbard Jul 22 '15 at 19:55
  • @MichaelHubbard You are converting a node to a string, and then a string to a node ? – Dici Jul 22 '15 at 19:57
  • Hmm, yes, I agree. I just went with what seemed to be the most probable class, based on the string example posted by OP in a comment to his question. – Chthonic Project Jul 22 '15 at 19:57
  • I'm converting an Object to a JsonObject that gets printed to a file, then later coming back and trying to recreate the Object from that JsonObject. However, in between getting the String and getting the JsonObject I'm running into problems I have never run into before--the exact same lines of code work elsewhere in the program. I'd say that maybe I put the test in the wrong directory or something, but it's not even referencing another one of my classes--it's entirely in Gson. – Michael Hubbard Jul 22 '15 at 19:59
  • @MichaelHubbard Did you get the solution for this problem ? I am also facing similar issue. When I view my my string on online json parser it is able to recreate jsn object but in code google.Gson() returns empty. – Pranjal Sahu Aug 11 '15 at 05:41
  • It ended up being a dependency issue, somehow. I recommend making sure you are using version 2.3.1 with a scope of "compile", if you're using Maven. – Michael Hubbard Aug 28 '15 at 19:04
0

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.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Irshu
  • 8,248
  • 8
  • 53
  • 65
0

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