如何在Java中将JSONObject写入其中包含JSONArray的文件? [英] How to write a JSONObject to a file, which has JSONArray inside it, in Java?

查看:174
本文介绍了如何在Java中将JSONObject写入其中包含JSONArray的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.simple 库在Java中使用JSON.

I use JSON.simple library to work with JSON in Java.

文件如下:

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

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

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

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

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();

这将输出:

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

如果我将数据存储在services之类的JSONArray中,该如何将JSON数据正确地写入文件?

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

代码,我从文件中读取JSON数据(效果很好):

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

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.

推荐答案

看看

Have a look at the examples of JSON-simple.

在这里说,您需要仅使用primitiveString值将对象逐一放入数组中.您可以像Map这样使用Collections,它们本身仅包含Stringprimitive值.

It says here that you need to put the Objects one by one into the Array, using only primitive and String values. You may use Collections like Map that by themselves only contain String or primitive values.

  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);

因此,不允许添加您的Services并且将无法使用.您应该在其中添加toMap方法,然后将其转换为MapfromMap并将其转换回.

So, adding your Services is not allowed and won't work. You should add a toMap method in it where you convert it to a Map and fromMap to convert it back.

赞(在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;
 }

然后您可以使用该Map这样填充JSONArray:

then you can use that Map to populate your JSONArray like this:

        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);

这篇关于如何在Java中将JSONObject写入其中包含JSONArray的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆