You can achieve this using bellow ways:
1. Using Jackson from Apache
String formattedData=new ObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(YOUR_JSON_OBJECT);
Import bellow class:
import com.fasterxml.jackson.databind.ObjectMapper;
It's gradle dependency is :
compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
2. Using Gson from Google
String formattedData=new GsonBuilder().setPrettyPrinting()
.create().toJson(YOUR_OBJECT);
Import bellow class:
import com.google.gson.Gson;
It's gradle is:
compile 'com.google.code.gson:gson:2.8.2'
Here, you can also download correct updated version from repository.