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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18977144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:01:30  来源:igfitidea点击:

How to parse JSON Array (Not Json Object) in Android

javaandroidjsongsonarrays

提问by SteBra

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 !

非常感激 !

采纳答案by Spring Breaker

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.

希望能帮助到你。

回答by Kevin Bowersox

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/

回答by nilkash

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

回答by TharakaNirmana

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 数组:[{"name":"name1","url":"url1"},{"name":"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");


}

回答by Maxim Shoustin

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

回答by vilpe89

I'll just give a little Hymansonexample:

我只举一个Hyman逊的小例子:

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

并解析 MyDataHolders 列表

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;

回答by TomCB

A few great suggestions are already mentioned. Using GSON is really handy indeed, and to make life even easier you can try this websiteIt'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 中提取对象变得更加容易!

回答by bong jae choe

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

希望有帮助

回答by Janus

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

}

}

回答by boyke purnomo

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