且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-05 08:35:58

看看

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