Reputation: 210
I am trying to create a JSON Object using com.google.code.jso
in JAVA 8. I have a list of objects and i am iterating through them. The object is as:
public class MyObject {
private String name, status, cause, id;
public String getName() {
return name;
}
public String getStatus() {
return status;
}
public String getCause() {
return cause;
}
public String getId() {
return id;
}
}
I have a list of above objects and i am trying to convert them to JSON using the below (the relevant code):
import com.google.gson.JsonObject;
JsonObject status = new JsonObject();
for (MyObject obj : objectLists){
status.add(obj.getId(),
new JsonObject()
.add("Name: ", obj.getName())
.add("Status: ", obj.getStatus())
.add("Cause: ", obj.getCause())
);
}
I was hoping to get a JSON of the following form:
{
"0 (this is the id i get from myObject.getId())": {
"name": The name i get from myObject.getName(),
"Status": The status from myobject.getStatus(),
"cause": The status from myobject.getCause()
},
"1": {
"name": "myname",
"Status": "mystatus",
"cause": "cause"
}
}
So I have 2 question.
I am getting an error in creating the Json object. Wrong 2nd
argument type. Found: 'java.lang.String', required:
'com.google.gson.JsonElement'
I understand that i have to change
the second parameter but i could not find in the docs how to do
that.
How can i pretty print this.
Thanks
Upvotes: 2
Views: 3541
Reputation: 4181
You used wrong method:
JsonObject.addProperty()
, not JsonObject.add()
JsonObject.add(String, JsonElement)
- adds nested json element to your object:
{
"root": {
"nested": {}
}
}
JsonObject.addProperty(String, String)
- adds property to your object (it may be any primitive or String):
{
"root": {
"property": "some string"
}
}
Upvotes: 3
Reputation: 5308
You should wrap your strings in JsonPrimitive
objects, for example:
new JsonObject().add("Name: ", new JsonPrimitive(obj.getName()));
To enable pretty printing, you have to use GsonBuilder.setPrettyPrinting()
:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(obj));
Upvotes: 1