【问题标题】:How do create a formatted json with Java?如何使用 Java 创建格式化的 json?
【发布时间】:2019-09-23 02:13:05
【问题描述】:

所以给定这些任意变量

String name = "bob";
List<String> hobby = new ArrayList<String>();
hobby.add("walk");
hobby.add("gym");
hobby.add("football");

如何输出字符串 json?上面的例子

{
    "name": "bob",
    "hobby": [
        "walk",
        "gym",
        "football"
    ]

}

我试过 JSONObject json = new JSONObject();但它没有按照我想要的方式正确格式化。

【问题讨论】:

  • 你用的是什么 json 库?您如何将上述对象转换为 json?
  • 我使用了 import org.json.JSONObject;至于转换,我只是将所有值都放入其中,但列表无法正常工作。
  • 图书馆的名字是什么? JSONObject是你自己写的吗?
  • 这可能是一个愚蠢的问题......但我该如何检查? JSONObject jsonKey = 新 JSONObject(); jsonKey.put("名称", 名称);导入让我使用它,这是我所知道的全部
  • 您使用的是什么 IDE?这是安卓吗?

标签: java json string


【解决方案1】:

据我所知,您必须自己处理列表 - 爱好 - 才能使用换行符打印它。但是在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));

控制台输出:

{
  "name" : "bob",
  "hobby" : [ "walk", "gym", "football" ]
}

【讨论】:

    【解决方案2】:

    如果你使用fasterxml jackson,那就很简单了。
    UPD1:用默认漂亮的打印机输出。

    @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
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      相关资源
      最近更新 更多