How to pretty print a complex Java object (e.g. with fields that are collections of objects)?
You could try and use Gson. it also serializes Arrays, Maps or whatever....
MyObject myObject = new MyObject();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
gson.toJson(myObject);
For deserialization use:
gson.fromJson(MyObject.class);
For typed maps see this answer: Gson: Is there an easier way to serialize a map
You can use the Jackson ObjectMapper
class is use to bind data with json. you can use it like below:
ObjectMapper mapper = new ObjectMapper();
you can save json into object like below
Object json = mapper.readValue(input,object.class);
you can write that in string variable
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
it should work fine.
You can use GSON
to convert your object to string. This will work for all the objects,
Gson gson = new Gson();
System.out.println(gson.toJson(objectYouWantToPrint).toString());