3

I have a json string:

 {  
   "id":123,
   "name":"",
   "details":{}
}

I want to parse to this object:

class Student {

int id;
String name; 
String details;

}

This is the error that I get:

java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.xxx/xxx.xxx.MainActivity}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT

The reason I want details as string not as a JsonObject because I'm using Realm DB object and persist that to the database. How can I tell Gson I want the details as string.

Jimmy
  • 10,427
  • 18
  • 67
  • 122
  • Your "json" isn't actually JSON - the field names aren't in quotes. It should be `{ "id": 123, "name": "", "details": {} }`. That *may* be all that's wrong. It would help if you'd show a short but complete program demonstrating the problem, mind you... – Jon Skeet Jul 06 '15 at 20:30
  • 1
    You can take the JSON Object and convert it to JSON String before saving in DB if you are question is with respect to only "details" attribute. – Wand Maker Jul 06 '15 at 20:32
  • `"details":{}` not compatible with `String details;` (that's what the error is telling you. It expects a String, but finds an Object, and bam.) – njzk2 Jul 06 '15 at 20:40

2 Answers2

1

The details value, {}, is an object not a string. It will not be interpreted as a string unless you quote it like this:

{
"id":123,
"name":"",
"details":"{}"
}

GSON is telling you "Expected STRING but was BEGIN_OBJECT". This makes sense, because you're giving it a type signature with a String attribute named details, but your serialization has an attribute named details that contains an empty object.

kdbanman
  • 10,161
  • 10
  • 46
  • 78
0

I didn't find a nice way to solve it but currently I copy the json object and stringify it to variable, remove it from the json element and then call gson fromJson.

Jimmy
  • 10,427
  • 18
  • 67
  • 122