10

I am struggling to generate JSON String in Java.

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

JSONArray ja = new JSONArray();
JSONObject js = new JSONObject();
JSONObject j = new JSONObject();

String s = "[{\"shakil\",\"29\",\"7676\"}]";

js.put("id", "1");
js.put("data", s);
ja.add(js);

j.put("rows", ja);

System.out.println(j.toString());

actual output:

{"rows":[{"id":"2","data":"[{\"shakil\",\"29\",\"7676\"}]"}]}

expected output:

{"rows":[{"id":"2","data":["shakil", "29","7676"]}]};
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
sunleo
  • 10,589
  • 35
  • 116
  • 196
  • 2
    the output you get seems to be correct, if I put a string in json, I expect it to remain a string, not be parsed. – Denis Tulskiy Nov 12 '12 at 08:35
  • @denis-tulskiy That's a fair expectation, but that's not what json-lib does. If a string value is parsable as JSON, json-lib will quietly parse it and put the JSON value instead. As an example, `System.out.println(new JSONObject().element("outer", "{\"inner\":\"value\"}"))` will print `{"outer":{"inner":"value"}}` and *not* `{"outer":"{\"inner\":\"value\"}"}`. See [line 245-271](https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/AbstractJSON.java#L245-L271) of `AbstractJSON` for details. – markusk Oct 02 '18 at 11:52

6 Answers6

22

Your s is a String which is not unquoted when put into a JSONObject. You must build another JSONArray for the value of data:

// using http://jettison.codehaus.org/
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();

innerArray.put("shakil");
innerArray.put("29");
innerArray.put("7676");

innerObject.put("id", "2");
innerObject.put("data", innerArray);

outerArray.put(innerObject);

outerObject.put("rows", outerArray);

System.out.println(outerObject.toString());

Result:

{
    "rows": [
        {
            "id": "2",
            "data": [
                "shakil",
                "29",
                "7676"
            ]
        }
    ]    
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • but I want to import net.sf.json.JSONArray and net.sf.json.JSONObject ,Is this possible to bring that structure using these packs. – sunleo Nov 12 '12 at 08:49
  • It should be easy to use the API of net.sf.json. The main point of my answer is that you have to construct *all* objects and arrays on *all* levels. Passing a quoted string doesn't work. –  Nov 12 '12 at 08:51
  • If I generate this kind of json structure only DHTMLX accepts.Thats why I am asking. – sunleo Nov 12 '12 at 08:53
10

Write

String[] s = new String[] {"shakil", "29" , "7676"};

instead of

String s = "[{\"shakil\",\"29\",\"7676\"}]";
Dims
  • 47,675
  • 117
  • 331
  • 600
1

Check out gson, it'll provide you with a whole lot of options for serializing/deserializing your Java objects to/from JSON.

Example taken from the page

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

//(Serialization)
gson.toJson(ints);     ==> prints [1,2,3,4,5]
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]

//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
resilva87
  • 3,325
  • 5
  • 32
  • 43
1

Finally found answer for net.sf.json

JSONArray data1 = new JSONArray();
data1.add("shakil");
data1.add("29");
data1.add("100");

JSONObject inner1 = new JSONObject();
inner1.put("id", "1");
inner1.put("data", data1);

JSONArray list2 = new JSONArray();
list2.add(inner1);

JSONObject finalObj = new JSONObject();
finalObj.put("rows", list2);

System.out.println(finalObj);
sunleo
  • 10,589
  • 35
  • 116
  • 196
1

Not being able to declare a JSON string in Java is huge pain. Mainly due to (a) no multiline strings (b) escaping double quotes makes it a mess wrt readability.

I work around this by using single quotes to declare the JSON string (using the standard multiline concatenation). Nothing fancy:

String jsonStr = 
    "{" +
        "'address': " + 
        "{" +
            "'name': '" + name + "'," +
            "'city': '" + city + "'," +
            "'street1': '"+ street1 +"'," +
            "'street2': '"+ street2 +"'," +
            "'zip': '" + zip + "', " +
            "'state':'" + state + "'," +
            "'country': '" + country + "'," +
            "'phone': '" + phone + "'" +
        "}" +
    "}";
jsonStr = MyUtil.requote(jsonStr);
System.out.println(jsonStr);

MyUtil

public static String requote(String jsonString) {
    return jsonString.replace('\'', '"');
}

Some might find this more cumbersome than declaring a Map but this works for me when I have to build a JSON with just string syntax.

Fakeer
  • 985
  • 1
  • 13
  • 29
1

I see a lot of problems when writing a json as String directly without using a Objectmapper or similar.

I would suggest you to write your Json (as you defined it):

{"rows":[{"id":"2","data":["shakil", "29","7676"]}]}

and then simply use this little online tool: http://www.jsonschema2pojo.org/

Which can convert a simply Json a Java-Class also with multiple classes. You can there choose during generation if you want to use Gson or Jackson later.

Gson is a little bit lightweighter and may is better for beginning. I prefer Jackson because you can create something like a computed property - but that's already to much detail.

https://code.google.com/p/google-gson/

After adding Gson all you need to do is:

Gson gson = new Gson();
MyGeneratedClass target = new MyGeneratedClass();
String json = gson.toJson(target);

As voila: you have generated a simple json without thinking about how to change it later!

DominikAngerer
  • 6,354
  • 5
  • 33
  • 60