更新时间:2023-11-05 08:35:58
Have a look at the examples of JSON-simple
.
在这里说,您需要仅使用primitive
和String
值将对象逐一放入数组中.您可以像Map
这样使用Collections
,它们本身仅包含String
或primitive
值.
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
方法,然后将其转换为Map
和fromMap
并将其转换回.
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);