如何在 JAVA 中解析 JSONObjects 的 JSONArray?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11101059/
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-10-31 03:47:58  来源:igfitidea点击:

How to parse a JSONArray of JSONObjects in JAVA?

javaandroidjsonarrays

提问by Andrei Stalbe

I have the following array returned to my JAVA Android application from PHP:

我将以下数组从 PHP 返回到我的 JAVA Android 应用程序:

Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );

In Java they above array looks like this:

在 Java 中,它们上面的数组如下所示:

{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};

For a simple JSONObject I'm using:

对于我正在使用的简单 JSONObject:

JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);

referral_fullname = finalResult.getString("referral_fullname");

but for an array of objects I don't know!

但是对于我不知道的一系列对象!

回答by Dheeresh Singh

String str = your Json-> apply to.String();

    JSONObject jObject  = new JSONObject(str);


    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = jObject.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = jObject .getString(key);
        map.put(key,value);
    }

回答by Houcine

Your Json Syntax is wrong , JSONArrayshould be like this :

你的 Json 语法是错误的,JSONArray应该是这样的:

["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];

and to parse a JsonArraythat contains some JSONObject, try this :

并解析JsonArray包含 some 的一个JSONObject,试试这个:

//parse the result
            JSONObject jsonResult = null;
            JSONArray arrayResult = null;
            ArrayList<YourObject> listObjects = null;
            try {
                arrayResult = new JSONArray(result);
                if(arrayResult != null) {
                    listObjects = new ArrayList<YourObject>();
                    int lenght = arrayResult.length();
                    for(int i=0; i< lenght; i++) {
                        JSONObject obj = arrayResult.getJSONObject(i);
                        YourObject object = new YourObject(obj);
                        listObjects.add(object);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

And add a constructor in your Class YourObjectto convert your Json to an instance :

并在您的类中添加一个构造函数YourObject以将您的 Json 转换为实例:

public YourObject(JSONObject json) {
    if (!json.isNull("referral_fullname"))
        this.referral_fullname = json.optString("referral_fullname", null);
    if (!json.isNull("referral_balance"))
        this.referral_balance = json.optString("referral_balance", null);
}

回答by Arcadien

You should use

你应该使用

JSONArray finalResult = new JSONArray(tokener);

if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like

如果你可以的话。您的结构现在是一个具有两个字段 0 和 1 的对象,其中包含另一个对象。如果你想像这样轻松迭代,你必须得到一个对象数组来代替这个复合对象

JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
  jso = finalResult.get(i);
  // jso == {"referral_fullname":"Name 1","referral_balance":"500"}

  [whatever]

}

回答by Kumar Vivek Mitra

Try this.............

试试这个.............

final JSONArray result_array = json.getJSONArray("result"); 

for (int i = 0; i < result.length(); i++) {

JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();

                    }

回答by RotatingWheel

First make an JSON object and see then in inner level what you have if you have array then fetch array. You need to make JSON object first. For example, if resp is a String (for example coming as http response)

首先创建一个 JSON 对象,然后在内部级别查看如果您有数组然后获取数组。您需要先制作 JSON 对象。例如,如果 resp 是一个字符串(例如作为 http 响应出现)

JSONObject jsonObject = new JSONObject(resp); 

jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response. If arraykey is a array inside the JSON objects then we can get list of array by the following way.

jsonObject 可能包含其他 JSON 对象或 JSON 数组。如何转换 JSON 取决于响应。如果 arraykey 是 JSON 对象中的数组,那么我们可以通过以下方式获取数组列表。

JSONArray arr  = jsonObject.getJSONArray("arraykey");

Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling

检查 arr 的长度,如果它大于 0,则它包含 JSON 对象或 JSON 数组,具体取决于数据。可以在http://www.hemelix.com/JSONHandling找到一个完整的示例,其中包含有关 JSON 字符串到 JSON 数组的一些解释