Reputation: 8135
I tried converting my json string to java object by using Gson but somehow it was not successful and I haven't figured out why..
My Json string
{
"JS":{
"JS0":{
"Name":"ABC",
"ID":"5"
},
"JS1":{
"Location":"UK",
"Town":"LD"
},
"JS2":{
"Usable":"true",
"Port":"ABC"
}
}
}
In java code I have 4 classes, JS, JS0, JS1 and JS2
JS class contains JS0, JS1 and JS2 variables
JS0, JS1 and JS2 classes contain fields as in Json string example, e.g. JS0 contains 02 fields, String Name and String ID
In all classes I have getter/setter for variables, 02 constructors (01 with empty parameters and another one with all variables in the parameter field)
And for using Gson:
Gson gson = new Gson();
jsObject = gson.fromJson(sb.toString(), JS.class);
When I access JS0, JS1 and JS2 objects from jsObject, they are null...
Can someone show me what did I do wrong?
Thank you very much,
Upvotes: 1
Views: 1125
Reputation: 1169
The problem here is, you are trying to convert
{
"JS" : {
/* rest of JSON */
}
}
to JS
object, but the above JSON is a representation of Java class like this
class Foo {
JS JS;
}
So, you need to get the value of JS
from the JSON string first, then call fromJSON
to deserialize it with the JS.class passed as the second parameter.
OR
Create a simple class containing only JS
as a variable, then call fromJSON
with that class passed as the second parameter of fromJSON
like this:
Java
class Foo {
JS JS;
}
jsObject = gson.fromJson(sb.toString(), Foo.class);
Upvotes: 2