如何在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字符串()