Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GsonBuilder setPrettyPrinting doesn't print pretty

Tags:

gson

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?

like image 927
1passenger Avatar asked Nov 16 '17 18:11

1passenger


2 Answers

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.

like image 88
nickb Avatar answered Nov 07 '22 20:11

nickb


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"
  ]
}
like image 28
1passenger Avatar answered Nov 07 '22 20:11

1passenger