I'm trying to build json using Gson dynamically as following , loop through existing fields and take the name and value and build json based on it,
so for an input:
a="AString"
B=true
C=null
D=[1,2,3]
E={"a":"b"}
will get valid json as:
{
"a":"AString",
"b": true,
"c": null,
"d":[1,2,3],
"e":{"a":"b"}
}
code:
JsonObject jsonObject = new JsonObject();
Field OutPortList[] = BBClass.class.getDeclaredFields();
for(Field x : OutPortList)
{
jsonObject.addProperty( x.getName() , x.get(this));
}
Getting error :
jsonObject.addProperty( String , String ) is not applicable
also tried casting :
jsonObject.addProperty( x.getName() , x.getType().cast(x.get(this)) );
Not sure but i guess it relate to type , as i try with x.get(this).toString() and its work but this will cast everything to string type. I'm not sure what would be the correct way to handle the type automatically without casting it each time to the correct type.
CodePudding user response:
You are trying to squeeze a java.lang.Object into a JsonElement (the add method) or a String (the addProperty method). The type of the field could be anything, including types that have no direct counterpart in json.
The easiest way would be to rely on the marshalling gson provides.
Gson gson = new Gson();
gson.toJson( this );
which yields a json formatted string.
If for some reason you still want to iterate the fields manually, you could still use gsons type marshalling for building the properties. Like this:
JsonObject jsonObject = new JsonObject();
Field[] OutPortList = Test.class.getDeclaredFields();
Gson gson = new Gson();
for(Field x : OutPortList)
{
jsonObject.add( x.getName(), gson.toJsonTree( x.get(this) ) );
}
Note, that you should consider sticking to Java naming conventions by using lowerCamelCase on variable names.
CodePudding user response:
Try this instead of add.
jsonObject.put( x.getName() , x.get(this));
it should work i think.
