如何在Android中解析JSON数组(而不是JSON对象)

时间:2022-10-22 20:37:28

I have a trouble finding a way how to parse JSONArray. It looks like this:

我很难找到一种解析JSONArray的方法。它看起来像这样:

[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects). But it's all I have and have to go with it.

如果JSON是以不同的方式编写的(换句话说,如果返回的是JSON对象而不是对象数组),我知道如何解析它。但这是我所拥有的一切,必须与之相伴。

*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out. There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.

*编辑:这是一个有效的json。我用这个json做了一个iPhone应用,现在我需要为Android做这个,但我搞不清楚。有很多例子,但是它们都是与JSONObject相关的。我需要一些JSONArray的东西。

Can somebody please give me some hint, or a tutorial or an example?

谁能给我一些提示,或者一个教程或者一个例子吗?

Much appreciated !

感谢!

10 个解决方案

#1


96  

use the following snippet to parse the JsonArray.

使用以下代码片段解析JsonArray。

JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    String name = jsonobject.getString("name");
    String url = jsonobject.getString("url");
}

Hope it helps.

希望它可以帮助。

#2


22  

I'll just give a little Jackson example:

我只举一个小杰克逊的例子:

First create a data holder which has the fields from JSON string

首先创建具有JSON字符串字段的数据保持器

// imports
// ...
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
    @JsonProperty("name")
    public String mName;

    @JsonProperty("url")
    public String mUrl;
}

And parse list of MyDataHolders

并解析mydataholder列表

String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString, 
    new TypeReference<ArrayList<MyDataHolder>>() {});

Using list items

使用列表项

String firstName = list.get(0).mName;
String secondName = list.get(1).mName;

#3


18  

public static void main(String[] args) throws JSONException {
    String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

    JSONArray jsonarray = new JSONArray(str);


    for(int i=0; i<jsonarray.length(); i++){
        JSONObject obj = jsonarray.getJSONObject(i);

        String name = obj.getString("name");
        String url = obj.getString("url");

        System.out.println(name);
        System.out.println(url);
    }   
}   

Output:

输出:

name1
url1
name2
url2

#4


9  

Create a class to hold the objects.

创建一个类来保存对象。

public class Person{
   private String name;
   private String url;
   //Get & Set methods for each field
}

Then deserialize as follows:

然后反序列化如下:

Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String

Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/

参考文章:http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/

#5


5  

In this example there are several objects inside one json array. That is,

在这个示例中,一个json数组中有几个对象。也就是说,

This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

这是json数组:[{“名称”:“name1”,“url”:“url1”},{“名称”:“name2”,“url”:“url2”},…]

This is one object: {"name":"name1","url":"url1"}

这是一个对象:{"name":"name1","url":"url1"}

Assuming that you have got the result to a String variable called jSonResultString:

假设您已经得到一个名为jSonResultString的字符串变量的结果:

JSONArray arr = new JSONArray(jSonResultString);

  //loop through each object
  for (int i=0; i<arr.length(); i++){

  JSONObject jsonProductObject = arr.getJSONObject(i);
  String name = jsonProductObject.getString("name");
  String url = jsonProductObject.getString("url");


}

#6


3  

@Stebra See this example. This may help you.

@Stebra看到这个例子。这可能会帮助你。

public class CustomerInfo 
{   
    @SerializedName("customerid")
    public String customerid;
    @SerializedName("picture")
    public String picture;

    @SerializedName("location")
    public String location;

    public CustomerInfo()
    {}
}

And when you get the result; parse like this

当你得到结果;这样的解析

List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());

#7


2  

A few great suggestions are already mentioned. Using GSON is really handy indeed, and to make life even easier you can try this website It's called jsonschema2pojo and does exactly that:

已经提到了一些很好的建议。使用GSON真的很方便,为了让生活更简单,你可以试试这个网站,叫做jsonschema2pojo

You give it your json and it generates a java object that can paste in your project. You can select GSON to annotate your variables, so extracting the object from your json gets even easier!

给它json,它就会生成一个java对象,可以在项目中粘贴。您可以选择GSON来注释您的变量,这样从json中提取对象就更容易了!

#8


1  

My case Load From Server Example..

我的案例来自服务器示例。

int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
            if (jsonLength != 1) {
                for (int i = 0; i < jsonLength; i++) {
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
                    JSONObject resJson = (JSONObject) jsonArray.get(i);
                    //addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
                }

Hope it help

希望它帮助

#9


-2  

            URL url = new URL("your URL");
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            //setting the json string
            String finalJson = buffer.toString();

            //this is your string get the pattern from buffer.
            JSONArray jsonarray = new JSONArray(finalJson);

#10


-3  

Old post I know, but unless I've misunderstood the question, this should do the trick:

我知道以前的帖子,但除非我误解了这个问题,否则这应该是一个好办法:

s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
    alert(array[i][index]);
}

}

}

#1


96  

use the following snippet to parse the JsonArray.

使用以下代码片段解析JsonArray。

JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    String name = jsonobject.getString("name");
    String url = jsonobject.getString("url");
}

Hope it helps.

希望它可以帮助。

#2


22  

I'll just give a little Jackson example:

我只举一个小杰克逊的例子:

First create a data holder which has the fields from JSON string

首先创建具有JSON字符串字段的数据保持器

// imports
// ...
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
    @JsonProperty("name")
    public String mName;

    @JsonProperty("url")
    public String mUrl;
}

And parse list of MyDataHolders

并解析mydataholder列表

String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString, 
    new TypeReference<ArrayList<MyDataHolder>>() {});

Using list items

使用列表项

String firstName = list.get(0).mName;
String secondName = list.get(1).mName;

#3


18  

public static void main(String[] args) throws JSONException {
    String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

    JSONArray jsonarray = new JSONArray(str);


    for(int i=0; i<jsonarray.length(); i++){
        JSONObject obj = jsonarray.getJSONObject(i);

        String name = obj.getString("name");
        String url = obj.getString("url");

        System.out.println(name);
        System.out.println(url);
    }   
}   

Output:

输出:

name1
url1
name2
url2

#4


9  

Create a class to hold the objects.

创建一个类来保存对象。

public class Person{
   private String name;
   private String url;
   //Get & Set methods for each field
}

Then deserialize as follows:

然后反序列化如下:

Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String

Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/

参考文章:http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/

#5


5  

In this example there are several objects inside one json array. That is,

在这个示例中,一个json数组中有几个对象。也就是说,

This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

这是json数组:[{“名称”:“name1”,“url”:“url1”},{“名称”:“name2”,“url”:“url2”},…]

This is one object: {"name":"name1","url":"url1"}

这是一个对象:{"name":"name1","url":"url1"}

Assuming that you have got the result to a String variable called jSonResultString:

假设您已经得到一个名为jSonResultString的字符串变量的结果:

JSONArray arr = new JSONArray(jSonResultString);

  //loop through each object
  for (int i=0; i<arr.length(); i++){

  JSONObject jsonProductObject = arr.getJSONObject(i);
  String name = jsonProductObject.getString("name");
  String url = jsonProductObject.getString("url");


}

#6


3  

@Stebra See this example. This may help you.

@Stebra看到这个例子。这可能会帮助你。

public class CustomerInfo 
{   
    @SerializedName("customerid")
    public String customerid;
    @SerializedName("picture")
    public String picture;

    @SerializedName("location")
    public String location;

    public CustomerInfo()
    {}
}

And when you get the result; parse like this

当你得到结果;这样的解析

List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());

#7


2  

A few great suggestions are already mentioned. Using GSON is really handy indeed, and to make life even easier you can try this website It's called jsonschema2pojo and does exactly that:

已经提到了一些很好的建议。使用GSON真的很方便,为了让生活更简单,你可以试试这个网站,叫做jsonschema2pojo

You give it your json and it generates a java object that can paste in your project. You can select GSON to annotate your variables, so extracting the object from your json gets even easier!

给它json,它就会生成一个java对象,可以在项目中粘贴。您可以选择GSON来注释您的变量,这样从json中提取对象就更容易了!

#8


1  

My case Load From Server Example..

我的案例来自服务器示例。

int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
            if (jsonLength != 1) {
                for (int i = 0; i < jsonLength; i++) {
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
                    JSONObject resJson = (JSONObject) jsonArray.get(i);
                    //addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
                }

Hope it help

希望它帮助

#9


-2  

            URL url = new URL("your URL");
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            //setting the json string
            String finalJson = buffer.toString();

            //this is your string get the pattern from buffer.
            JSONArray jsonarray = new JSONArray(finalJson);

#10


-3  

Old post I know, but unless I've misunderstood the question, this should do the trick:

我知道以前的帖子,但除非我误解了这个问题,否则这应该是一个好办法:

s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
    alert(array[i][index]);
}

}

}