【问题标题】:How to make my JSON nicer in java ? Strictly using - org.json.JSON如何在 java 中使我的 JSON 更好?严格使用 - org.json.JSON
【发布时间】:2020-01-24 07:50:37
【问题描述】:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class testjson {

    public static void main(String args[]) throws JSONException {
        JSONObject json = new JSONObject();
        json.put("name", "timmy");
        json.put("age", "20");

        List<String> ids = new ArrayList<>(); 
        JSONObject jsonIds = new JSONObject();

        jsonIds.put("jobId", "123");
        jsonIds.put("houseId", "5");


        ids.add(jsonIds.toString(4));

        json.put("idList", ids);

        System.out.println(json.toString(4));

    }

}

我想把它打印出来。它的顺序无关紧要,但也要修复数组。

{
    "age": "20",
    "name": "timmy",
    "idList": [
        {
            "houseId": "5", 
            "jobId": "123"
        }
    ]

}

目前这个输出

{
    "age": "20",
    "idList": ["{\n    \"houseId\": \"5\",\n    \"jobId\": \"123\"\n}"],
    "name": "timmy"
}

如您所见,idList 不是我想要的。我试着玩弄它,但没有任何效果。有谁知道这个标准 json 库是否可行?或者 Eclipse 拥有的任何其他库,我不必像 jackson 或 gson 那样单独下载

【问题讨论】:

    标签: java json string list


    【解决方案1】:

    在创建JSON Object 时不要使用toString。做一次,最后当整个 JSON 被创建时。

    在你的代码中应该是:

    ids.add(jsonIds);
    

    以下代码:

    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class OrgJsonApp {
      public static void main(String[] args) {
          JSONObject root = new JSONObject();
          root.put("name", "timmy");
          root.put("age", "20");
    
    
          JSONObject ids = new JSONObject();
          ids.put("jobId", "123");
          ids.put("houseId", "5");
    
          JSONArray idList = new JSONArray();
          idList.put(ids);
    
          root.put("idList", idList);
    
          System.out.println(root.toString(4));
      }
    }
    

    打印:

    {
        "name": "timmy",
        "idList": [{
            "jobId": "123",
            "houseId": "5"
        }],
        "age": "20"
    }
    

    改变数组的格式并不容易,需要扩展基类。最简单的方法是创建org.json 包:

    package org.json;
    
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Iterator;
    
    public class JSONArrayIndent extends JSONArray {
    
        @Override
        public Writer write(Writer writer, int indentFactor, int indent) throws JSONException {
            try {
                boolean commanate = false;
                int length = this.length();
                writer.write('[');
    
                if (length > 0) {
                    final int newindent = indent + indentFactor;
    
                    Iterator<Object> iterator = iterator();
                    while (iterator.hasNext()) {
                        Object next = iterator.next();
                        if (commanate) {
                            writer.write(',');
                        }
                        if (indentFactor > 0) {
                            writer.write('\n');
                        }
                        JSONObject.indent(writer, newindent);
                        try {
                            JSONObject.writeValue(writer, next,
                                indentFactor, newindent);
                        } catch (Exception e) {
                            throw new JSONException("Unable to write JSONArray value: " + next, e);
                        }
                        commanate = true;
                    }
                    if (indentFactor > 0) {
                        writer.write('\n');
                    }
                    JSONObject.indent(writer, indent);
                }
                writer.write(']');
                return writer;
            } catch (IOException e) {
                throw new JSONException(e);
            }
        }
    }
    

    在上面的例子中改变一行:

    JSONArray idList = new JSONArrayIndent();
    

    然后打印:

    {
        "name": "timmy",
        "idList": [
            {
                "jobId": "123",
                "houseId": "5"
            }
        ],
        "age": "20"
    }
    

    但我不确定它是否值得,因为JSON 缩进不会改变客户端-服务器通信中的任何内容。此外,我们应该让JSON 有效负载尽可能小,并且只在需要时对其进行格式化。

    【讨论】:

    • 不是我想要的。看起来比我的好,但数组括号不是 4 行 gyazo.com/63e22629478e2f4bca5a7f5fd5bff82f
    • @bob 它不仅看起来比您的更好,而且是您想要的正确 JSON(而您的不是,它破坏了嵌套对象)。格式有那么重要吗?
    • @bob,数组如何打印到JSONJSONArray.write 方法中定义。如果您在数组中有一个元素,则如示例所示,当您有两个或更多对象时,它就是您想要的。
    • 哦,我明白了,它按预期工作。无论如何要解决这个 1 阵列问题?除非这也是 1 元素 json 的正确 json 格式
    【解决方案2】:

    org.json 类只允许您设置起始缩进级别,以及每个级别的空格数。而已。

    正如您所发现的,您无法通过格式化嵌套数组并将它们拼接在一起来解决问题。 org.json API 不支持此功能。


    我尝试寻找提供更好(更灵活)漂亮打印的替代品。如果有的话,GSON 就更不灵活了。相比之下,Jackson 库提供了一个PrettyPrinter 接口和基类,您可以使用它们来实现您自己的自定义漂亮打印机。然后,您可以使用您的自定义类来实例化ObjectWriter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-27
      • 2014-03-15
      • 2012-12-29
      • 1970-01-01
      • 2016-10-24
      • 2019-10-05
      • 2018-07-19
      • 1970-01-01
      相关资源
      最近更新 更多