GsonBuilder setPrettyPrinting doesn't print pretty

I'm using the following code (found on this webpage) and the Gson library (2.8.2) to format JSON code with pretty printing.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonExample {
    public static void main(String[] args) {
      String jsonData = "{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}";

      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String json = gson.toJson(jsonData);

      System.out.println(json);
    }
}

This is the expected result:

{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}

Unfortunately "pretty printing" doesn't work at all and I get everything in one line:

{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}"

Any ideas what I'm doing wrong?


You have to parse the JSON, and then call gson.toJson() on the resulting parsed JSON.

JsonElement jsonElement = new JsonParser().parse(jsonData);
String json = gson.toJson(jsonElement);

Your current code is just telling GSON to convert some String into JSON, and the result of that is the same String.


nickb made my day! :-)

The correct code must look like this:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;

public class GsonExample {
    public static void main(String[] args) {
      String jsonData = "{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}";
      JsonElement jsonElement = new JsonParser().parse(jsonData);

      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String json = gson.toJson(jsonElement);

      System.out.println(json);
    }
}

Output:

{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}