简体   繁体   English

使用 Java 格式化输出的 JSON

[英]Formatting JSON for output with Java

I have a JSON object that looks like this:我有一个如下所示的 JSON 对象:

{
    "Person":{
        "Name":"Johnny Doe",
        "Age":30,
        "Gender":"Female",
        "Address":{
            "Number":10,
            "Line1":"Downing Street",
            "City":"London",
            "Country":"UK"
        },
        "PhoneNumbers":{
            "Number":"999"
        }
    }
}

How can I iterate through the data so I can produce a nice, formatted output that looks like this?我如何遍历数据,以便生成看起来像这样的漂亮的格式化输出?

Person
    Name: Johnny Doe
    Age: 30
    Gender: Female
    Address
        Number: 10
        Line1: Downing Street
        City: London
        Country: UK
    PhoneNumbers
        Number: 999

Thanks in advance for any help.在此先感谢您的帮助。

Have a look at this link to find different JSON parsers available in java.查看此链接以查找 Java 中可用的不同 JSON 解析器。 You could select one and use that to parse the json into some sort of map and then iterate through to print the conten the way you want.您可以选择一个并使用它来将 json 解析为某种地图,然后迭代以您想要的方式打印内容。

JSONObject has a toString method which output a string like your first representation. JSONObject 有一个 toString 方法,它输出一个像你的第一个表示一样的字符串。 See doc : http://www.json.org/javadoc/org/json/JSONObject.html#toString%28int%29见文档: http : //www.json.org/javadoc/org/json/JSONObject.html#toString%28int%29

You can adjust indentation.您可以调整缩进。

Then, you will just have to delete (via replace) '{', '}', ',', and '"' characters.然后,您只需删除(通过替换)'{'、'}'、',' 和 '"' 字符。

Apolo阿波罗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM