如何在 Java 中将 JSONObject 写入其中包含 JSONArray 的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19211441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:05:45  来源:igfitidea点击:

How to write a JSONObject to a file, which has JSONArray inside it, in Java?

javajsonjsonobjectjson-simple

提问by alena_fox_spb

I have JSON file, that I need to read, edit and write out again.

我有 JSON 文件,我需要再次读取、编辑和写出。

Reading works fine, I struggle with the write part of the JSON Array in my data.

读取工作正常,我在我的数据中处理 JSON 数组的写入部分。

I use JSON.simplelibrary to work with JSON in Java.

我使用JSON.simple库来处理 Java 中的 JSON。

The file looks like this:

该文件如下所示:

{
    "maxUsers":100,
    "maxTextLength":2000,
    "maxFileSize":2000,
    "services":
    [
        {
            "serviceName":"Яндекc",
            "className":"YandexConnector.class",
            "isEnabled":true
        },

        {
            "serviceName":"Google",
            "className":"GoogleConnector.class",
            "isEnabled":false
        }
    ]
}

When I try to write JSON-data (variable obj) to file, the servicesarray is broken. My writing code:

当我尝试将 JSON 数据(变量obj)写入文件时,services数组已损坏。我的写作代码:

JSONObject obj = new JSONObject();
obj.put("maxUsers", this.getMaxUsers());
obj.put("maxTextLength", this.getMaxTextLength());
obj.put("maxFileSize", this.getMaxFileSize()); 

JSONArray servicesJSON = new JSONArray();
ArrayList<Service> servicesArray = this.getServices();
for(int i=0; i< servicesArray.size(); i++)
{
    servicesJSON.add(servicesArray.get(i));
}
obj.put("services", servicesJSON);


FileWriter file = new FileWriter(filename);                
obj.writeJSONString(file);
file.flush();
file.close();

This outputs:

这输出:

{
    "services":
    [
        translator.settings.Service@121c5df,
        translator.settings.Service@45f4ae
    ],
    "maxTextLength":2000,
    "maxUsers":100,
    "maxFileSize":2000
}

How can I write the JSON data correctly to a file, if I have it in a JSONArray like services?

如果我将 JSON 数据放在 JSONArray 中,如何将其正确写入文件services



The code, where I read the JSON data from the file (that works fine):

我从文件中读取 JSON 数据的代码(工作正常):

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filename));
JSONObject jsonObject = (JSONObject) obj;

setMaxUsers((Long) jsonObject.get("maxUsers"));
setMaxTextLength((Long) jsonObject.get("maxTextLength"));
setMaxFileSize((Long) jsonObject.get("maxFileSize"));
// get all list of services
JSONArray serv = (JSONArray) jsonObject.get("services");

for (int i = 0; i < serv.size(); i++) {
    JSONObject service = (JSONObject) serv.get(i);
    Service servec = new Service();
    servec.setServiceName((String) service.get("serviceName"));
    servec.setClassName((String) service.get("className"));
    servec.setIsEnabled((Boolean) service.get("isEnabled"));

    services.add(i, servec);
}

The editing part is not yet written, so I call the writing part directly after the reading.

编辑部分还没有写,所以我在阅读后直接调用写作部分。



采纳答案by Angelo Fuchs

Have a look at the examplesof JSON-simple.

看一看的例子JSON-simple

It says here that you need to put the Objects one by one into the Array, using only primitiveand Stringvalues. You may use Collectionslike Mapthat by themselves only contain Stringor primitivevalues.

它在这里说您需要将对象一个一个地放入数组中,仅使用primitiveString值。您可以使用CollectionslikeMap本身只包含Stringprimitive值。

  JSONArray list = new JSONArray();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  StringWriter out = new StringWriter();
  list.writeJSONString(out);

So, adding your Servicesis not allowed and won't work. You should add a toMapmethod in it where you convert it to a Mapand fromMapto convert it back.

因此,添加您的内容Services是不允许的,也不会起作用。您应该toMap在其中添加一个方法,将其转换为 aMap并将fromMap其转换回。

Like this (in Services.java):

像这样(在Services.java):

 public Map toMap() {
     HashMap<String, String> serviceAsMap = new HashMap<>();
     servicesAsMap.put("serviceName", serviceName);
     servicesAsMap.put("className", this.class.getName() + ".class");
     servicesAsMap.put("isEnabled", isEnabled);
     // ... continue for all values
     return servicesAsMap;
 }

then you can use that Mapto populate your JSONArraylike this:

然后你可以用它Map来填充你的JSONArray样子:

        JSONArray servicesJSON = new JSONArray();
        ArrayList<Service> servicesArray = this.getServices();
        for(int i=0; i< servicesArray.size(); i++)
        {
            servicesJSON.add(servicesArray.get(i).toMap()); // use the toMap method here.
        }
        obj.put("services", servicesJSON);

回答by PyDevSRS

Have a look at JSONArray Documentation.Here you will get list of methods available.This JSONArrayis inherited from java.util.ArrayList,so we can use the methods available for ArrayListto JSONArray.

查看 JSONArray文档。在这里您将获得可用方法的列表。这JSONArray是从 继承的java.util.ArrayList,因此我们可以使用可用于ArrayListto的方法JSONArray

 JSONArray userList = JSONFile.readJSONArray("users.json");
 JSONArray newuserList = new JSONArray() ;  
 JSONObject jsonobject , newjsonObject;
            for (int i = 0; i < userList.size(); i++) {
                jsonobject = (JSONObject) userList.get(i);

                String id = (String) jsonObject.get("id");
                String pass = (String) jsonObject.get("password");
                newuserList.add(jsonObject); 
 // Here we are putting json object into newuserList which is of JSONArray type
            try{
                FileWriter  file = new FileWriter( "/users.json",false);

                newuserList.writeJSONString(newuserList, file);
                file.close();
            }
            catch(Exception e  ){

                e.getMessage();

            }

Hope this will help !

希望这会有所帮助!