How to format JSON string in java?

I have a jersey client that receives JSON from the source I need to get properly formatted JSON:

My JSON String is as follows: grabbing it via http request:

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

I have problems because json must be formatted correctly and keyA, keB and keyC are not surrounded by quotation marks. Is there any library that helps add quotes or some better way to turn this string into properly formatted json? Or if there is an easy way to convert this to a json object without writing a group of classes with variables and lists that match the incoming structure?

+4
source share
4 answers

you can use json-lib . it is very comfortable! you can build your json string as follows:

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

+4
source

I like Flexjson and many initializers :

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

leads to:

 { "properties": [ { "someproperty": "aproperty", "set of dada": { "keyA": "SomeValueA", "keyB": "SomeValueB", "keyC": "SomeValueC" } } ] } 
+3
source

Your string is not JSON. This is something like JSON. There is no form of JSON that makes these quotes optional. AFAIK, there is no library that will read your string and deal with missing quotes, and then rotate it back correctly. You need to find the code that created this and fix it to create real JSON.

+3
source

You can use argo , a simple parser and JSON generator in Java

0
source

All Articles