Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

How to generate JSON string in Java using net.sf.json?

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"]}]};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...