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

前端 未结 6 1757
北海茫月
北海茫月 2020-12-01 14:56

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          


        
相关标签:
6条回答
  • 2020-12-01 15:39

    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!

    0 讨论(0)
  • 2020-12-01 15:40

    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.

    0 讨论(0)
  • 2020-12-01 15:41

    Write

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

    instead of

    String s = "[{\"shakil\",\"29\",\"7676\"}]";
    
    0 讨论(0)
  • 2020-12-01 15:43

    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);
    
    0 讨论(0)
  • 2020-12-01 15:46

    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"
                ]
            }
        ]    
    }
    
    0 讨论(0)
  • 2020-12-01 16:00

    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);
    
    0 讨论(0)
提交回复
热议问题