Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly format JSON string in java?

Tags:

java

json

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

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"
            }
        }
    ]
}

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?

like image 416
Rolando Avatar asked Jun 20 '12 01:06

Rolando


2 Answers

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);

and of course you can get your JSON String simply by calling properties.toString()

like image 110
Cruis Avatar answered Oct 06 '22 07:10

Cruis


I like Flexjson, and using lots of initilizers:

  public static void main(String[] args) {

    Map<String, Object> object = new HashMap<String, Object>() {
        {
            put("properties", new Object[] { new HashMap<String, Object>() {
                {
                    put("someproperty", "aproperty");
                    put("set of dada", new HashMap<String, Object>() {
                        {
                            put("keyA", "SomeValueA");
                            put("keyB", "SomeValueB");
                            put("keyC", "SomeValueC");
                        }
                    });
                }
            } });
        }
    };

    JSONSerializer json = new JSONSerializer();
    json.prettyPrint(true);
    System.out.println(json.deepSerialize(object));
  }

results in:

{
  "properties": [
    {
        "someproperty": "aproperty",
        "set of dada": {
            "keyA": "SomeValueA",
            "keyB": "SomeValueB",
            "keyC": "SomeValueC"
        }
    }
  ]
}
like image 32
Martín Schonaker Avatar answered Oct 06 '22 07:10

Martín Schonaker