有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将JSON对象作为对象而不是字符串写入文件

我想将JSON对象写入文件。目前,我尝试使用ObjectMapper和Gson,但他们将JSON编写为JSONString,因此输出文件具有JSON字符串而不是对象。那么,有没有一种方式可以将JSON对象写成对象而不是字符串呢

JSONObject responseData = new JSONObject(response.getBody().toString());
org.json.simple.JSONObject object  = new
org.json.simple.JSONObject(responseData.toMap());
ObjectMapper objMapper = new ObjectMapper();
objMapper.writeValue(new File(path) , object);

现在,上面的代码将JSON对象作为字符串写入文件,而不是JSONObject


共 (1) 个答案

  1. # 1 楼答案

    不要使用ObjectMapper。您可以通过org实现这一点。json。简单。*包装本身

        package com.tutorial
    
        import java.io.FileWriter;
        import java.io.IOException;
    
        import org.json.simple.JSONObject;
    
        public class JosnObjectWrite {
    
            public static void main(String[] args) throws IOException {
    
                JSONObject responseData = new JSONObject(response.getBody().toString());
                JSONObject object  = new JSONObject(responseData.toMap());
    
                try (FileWriter file = new FileWriter("/Users/<username>/Documents/file1.txt")) {
                    file.write(object.toJSONString());
                    System.out.println("Successfully Copied JSON Object to File...");
                    System.out.println("\nJSON Object: " + object);
                }
            }
        }