So given these arbitrary variables
String name = "bob";
List<String> hobby = new ArrayList<String>();
hobby.add("walk");
hobby.add("gym");
hobby.add("football");
How do I output a String json? Example of above
{
"name": "bob",
"hobby": [
"walk",
"gym",
"football"
]
}
I've tried JSONObject json = new JSONObject(); but with that it wasn't properly formatted the way I wanted.
As far as I know, you have to handle the list - hobby - by yourself to print it with newline. But with the help of Gson
(Google Gson), you can print them as you expected as follows.
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", name);
jsonObj.put("hobby", hobby);
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonObj.toString()).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(json));
Then the console out is going to be
{
"name": "bob",
"hobby": [
"walk",
"gym",
"football"
]
}
UPDATED
If you use writerWithDefaultPrettyPrinter()
in Jackson2 library, it seems not to print Json array as same as Gson
.
ObjectMapper mapper = new ObjectMapper();
Object jsonObj1 = mapper.readValue(jsonObj.toString(), Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObj1));
Console output:
{
"name" : "bob",
"hobby" : [ "walk", "gym", "football" ]
}
If you use fasterxml jackson, it would be very easy.
UPD1: output with default pretty printer.
@Test
public void test01() {
String name = "bob";
List<String> hobby = new ArrayList<String>();
hobby.add("walk");
hobby.add("gym");
hobby.add("football");
// create a class with name and hobby property
Demo demo = new Demo();
demo.setName(name);
demo.setHobby(hobby);
ObjectMapper objectMapper = new ObjectMapper();
try {
String result = objectMapper.writeValueAsString(demo);
System.out.println(result);
//{"name":"bob","hobby":["walk","gym","football"]}
String prettyResult = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(demo);
System.out.println(prettyResult);
// {
// "name" : "bob",
// "hobby" : [ "walk", "gym", "football" ]
// }
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
static class Demo {
private String name;
private List<String> hobby;
//getter/setter
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.