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"]}]};
2
  • 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. Commented Nov 12, 2012 at 8: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 of AbstractJSON for details. Commented Oct 2, 2018 at 11:52

6 Answers 6

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"
            ]
        }
    ]    
}
Sign up to request clarification or add additional context in comments.

3 Comments

but I want to import net.sf.json.JSONArray and net.sf.json.JSONObject ,Is this possible to bring that structure using these packs.
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.
If I generate this kind of json structure only DHTMLX accepts.Thats why I am asking.
10

Write

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

instead of

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

Comments

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

Comments

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

Comments

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.

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.