[英]How do create a formatted json with Java?
所以给定这些任意变量
String name = "bob";
List<String> hobby = new ArrayList<String>();
hobby.add("walk");
hobby.add("gym");
hobby.add("football");
我如何 output 字符串 json? 上面的例子
{
"name": "bob",
"hobby": [
"walk",
"gym",
"football"
]
}
我试过 JSONObject json = new JSONObject(); 但它没有按照我想要的方式正确格式化。
据我所知,您必须自己处理列表 -爱好- 才能用换行符打印它。 但是在Gson
(Google Gson) 的帮助下,您可以按如下方式打印它们。
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));
然后控制台输出将是
{
"name": "bob",
"hobby": [
"walk",
"gym",
"football"
]
}
更新
如果您在 Jackson2 库中使用writerWithDefaultPrettyPrinter()
,似乎不会像Gson
一样打印 Json 数组。
ObjectMapper mapper = new ObjectMapper();
Object jsonObj1 = mapper.readValue(jsonObj.toString(), Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObj1));
控制台 output:
{
"name" : "bob",
"hobby" : [ "walk", "gym", "football" ]
}
如果使用fasterxml jackson,那就很简单了。
UPD1: output,带有默认的漂亮打印机。
@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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.