25

我正在尝试在 android 上创建这个 JSON 对象。我被困在如何在对象中添加字符串数组。

A = {
    "class" : "4" ,
    "name" : ["john", "mat", "jason", "matthew"]
    }

这是我写的代码:

import org.json.JSONObject;

JSONObject school = new JSONObject();

school.put("class","4");
school.put("name", ["john", "mat", "jason", "matthew"] );

但是最后一行给出了一个错误。有办法过去吗?

4

5 回答 5

56

汤姆建议的一点不恰当的方法。优化后的代码是:

ArrayList<String> list = new ArrayList<String>();
list.add("john");
list.add("mat");
list.add("jason");
list.add("matthew");

JSONObject school = new JSONObject();

school.put("class","4");
school.put("name", new JSONArray(list));
于 2013-10-16T12:20:10.797 回答
6

您收到错误是因为您的最后一行是无效的 Java。

school.put("name", new JSONArray("[\"john\", \"mat\", \"jason\", \"matthew\"]"));
于 2013-03-31T13:10:45.233 回答
3

因此,您会遇到错误。

school.put("name", ["john", "mat", "jason", "matthew"] );
                   ^                                 ^   

这样做。

school.put("name", new JSONArray("[\"john\", \"mat\", \"jason\", \"matthew\"]"));
于 2013-03-31T13:00:54.533 回答
2

@bhavindesai,答案很好。这是解决此问题的另一种方法。您可以使用 Json Simple 库简单地做到这一点。这是毕业典礼

compile 'com.googlecode.json-simple:json-simple:1.1'

这是示例代码:

org.json.simple.JSONObject jsonObject=new org.json.simple.JSONObject();
jsonObject.put("Object","String Object");

ArrayList<String> list = new ArrayList<String>();
            list.add("john");
            list.add("mat");
            list.add("jason");
            list.add("matthew");

            jsonObject.put("List",list);

就是这样。:)

于 2016-03-23T07:45:32.630 回答
2

正如 bhavindesai 指出的那样,

ArrayList<String> list = new ArrayList<String>();
list.add("john");
list.add("mat");
list.add("jason");
list.add("matthew");

JSONObject school = new JSONObject();

school.put("class","4");
school.put("name", new JSONArray(list));

是一种更好,更清洁的方法。

要导入正确的包,您应该编写:

import org.json.simple.JSONArray;

在java类之上。

如果您使用的是 Maven,请添加

 <dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1</version>  
</dependency>

到 pom.xml。然后,下载源和依赖项并重新导入。尽管我使用了评论,但我还是回答了,因为评论搞砸了代码缩进。

于 2019-11-27T09:02:50.947 回答