简体   繁体   English

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

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

I have a trouble finding a way how to parse JSONArray.我很难找到解析 JSONArray 的方法。 It looks like this:它看起来像这样:

[{"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).如果 JSON 的编写方式不同,我知道如何解析它(换句话说,如果我返回的是 json 对象而不是对象数组)。 But it's all I have and have to go with it.但这就是我所拥有的,并且必须随它去。

*EDIT: It is a valid json. *编辑:这是一个有效的 json。 I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.我使用这个 json 制作了一个 iPhone 应用程序,现在我需要为 Android 做它并且无法弄清楚。 There are a lot of examples out there, but they are all JSONObject related.有很多例子,但它们都与 JSONObject 相关。 I need something for JSONArray.我需要一些 JSONArray 的东西。

Can somebody please give me some hint, or a tutorial or an example?有人可以给我一些提示,或者教程或示例吗?

Much appreciated !非常感激 !

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

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并解析 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;
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

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/

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

In this example there are several objects inside one json array.在此示例中,一个 json 数组中有多个对象。 That is,那是,

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


}

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.你给它你的 json,它会生成一个可以粘贴到你的项目中的 java 对象。 You can select GSON to annotate your variables, so extracting the object from your json gets even easier!您可以选择 GSON 来注释您的变量,因此从您的 json 中提取对象变得更加容易!

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

Create a POJO Java Class for the objects in the list like so:为列表中的对象创建一个 POJO Java 类,如下所示:

class NameUrlClass{
       private String name;
       private String url;
       //Constructor
       public NameUrlClass(String name,String url){
              this.name = name;
              this.url = url; 
        }
}

Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:现在只需创建一个 NameUrlClass 列表并将其初始化为一个 ArrayList ,如下所示:

List<NameUrlClass> obj = new ArrayList<NameUrlClass>;

You can use store the JSON array in this object您可以使用将 JSON 数组存储在此对象中

obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]

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

} }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM