toJSONString() is undefined for the type JSONObject

前端 未结 4 1566
情歌与酒
情歌与酒 2021-01-02 15:21

My code to create a new JSONObject and write to a file:

JSONObject obj = new JSONObject();
obj.put(\"name\", \"abcd\");
obj.put(\"age\", new Integer(100));
J         


        
4条回答
  •  醉酒成梦
    2021-01-02 15:58

    Simply stringifying the JsonObject will not work. Using json-simple 3.1.0, JsonObject.toString() will not write the object as valid JSON.

    Given the JSON Object as:

    JsonObject my_obj = new JsonObject();
    my_obj.put("a", 1);
    my_obj.put("b", "z");
    my_obj.put("c", true);
    
    file.write(my_obj.toString());
    

    Will save as

    {a=1, b=z, c=true}
    

    Which is not valid JSON.

    To fix this, you need to use the Jsoner.

    Working Example

    import com.github.cliftonlabs.json_simple.JsonObject;
    import com.github.cliftonlabs.json_simple.Jsoner;
    
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class Example {
    
        public static void main(String args[]) {
            JsonObject my_obj = new JsonObject();
            my_obj.put("a", 1);
            my_obj.put("b", "z");
            my_obj.put("c", true);
    
            try {
                BufferedWriter writer = Files.newBufferedWriter(Paths.get("test.json"));
                Jsoner.serialize(my_obj, writer);
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    

    Which saves as

    {"a":1,"b":"z","c":true}
    

    Which is valid JSON.

提交回复
热议问题