Home > Blockchain >  JSON Object empty when creating it from a String
JSON Object empty when creating it from a String

Time:01-14

I'm trying to create a JSON Object from a String. The String looks like this: {"case":"getAllProducts"}.

Why is jobj always empty?

String received = textMessage.getText();
            
System.out.println(received);       //{"case":"getAllProducts"} - perfect
            
JsonObject jobj = new Gson().fromJson(received, JsonObject.class);
            
System.out.println(jobj);           //{} - why empty???
            
String reqCase = jobj.get("case").getAsString();

I already checked out other articles here where its done exactly like I did. I can't find my problem here..

CodePudding user response:

Instead of

new Gson().fromJson(received, JsonObject.class);

it should be

new Gson().fromJson(received, YourClass.class);

where YourClass is a user defined class having attributes same as the attributes in your JSON.

  •  Tags:  
  • Related