如何在java中正确格式化JSON字符串? [英] How to properly format JSON string in java?

查看:613
本文介绍了如何在java中正确格式化JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泽西客户端从我需要进入格式正确的JSON的源码获取JSON:

I have a jersey client that is getting JSON from a source that I need to get into properly formatted JSON:

我的JSON字符串看起来像抓住它时的下一个通过http请求:

My JSON String looks like the folllowing when grabbing it via http request:

{
    "properties": [
        {
            someproperty: "aproperty",
            set of data: {
                keyA: "SomeValueA",
                keyB: "SomeValueB",
                keyC: "SomeValueC"
            }
        }
    ]
}

因为json必须是格式正确,keyA,keB和keyC不用引号括起来。是否有一些库可以帮助添加引号或一些最好的方法来将此字符串转换为格式正确的json?或者,如果有一些简单的方法将其转换为json对象而不编写一堆具有与传入结构匹配的变量和列表的类?

I am having problems because the json has to be properly formatted and keyA, keB, and keyC are not surrounded in quotes. Is there some library that helps add quotes or some best way to go about turning this string to properly formatted json? Or if there is some easy way to convert this to a json object without writing a bunch of classes with variables and lists that match the incoming structure?

推荐答案

您可以使用 json-lib 。这很方便!你可以像这样构造你的json字符串:

you can use json-lib. it's very convenient! you can construct your json string like this:

JSONObject dataSet = new JSONObject();
dataSet.put("keyA", "SomeValueA") ;
dataSet.put("keyB", "SomeValueB") ;
dataSet.put("keyC", "SomeValueC") ;

JSONObject someProperty = new JSONObject();
dataSet.put("someproperty", "aproperty") ;

JSONArray properties = new JSONArray();
properties.add(dataSet);
properties.add(someProperty);

当然你只需调用 properties.toString即可获得你的JSON字符串()

这篇关于如何在java中正确格式化JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆