如何从JSON数组中获取对象?

时间:2015-02-16 12:36:46

标签: android arrays json

从这个JSON数组中,我必须获取值Q889?如何获得它?

[{
    "Policy_Id": "199",
    "Status_Eng": "Approved",
    "INFO": [
        {
            "Caption": "Chs No",
            "Val": "Q8"
        },
        {
            "Caption": "Reg No",
            "Val": "89"
        },
        {
            "Caption": "Year",
            "Val": "06"
        },
        {
            "Caption": "Me",
            "Val": "hun"
        },
        {
            "Caption": "Mol",
            "Val": "hhh"
        }
    ]
}]

我目前的代码:

for (int i = 0; i < array.length(); i++) {
    JSONObject jboj = array.getJSONObject(i);
    para = new Quote();
    para.pol_status = jboj.getString("Status_Eng");

    JSONArray array1 = jboj.getJSONArray("INFO");

    for (int j = 0; j < array1.length(); j++) {
        JSONObject jObj1 = array1.getJSONObject(j);
        para.cnum = jObj1.getString("Val").toString();
        para.cnum = jObj1.getString("Val").toString();
    }
}

5 个答案:

答案 0 :(得分:1)

将所有值保存到列表

List<String> listOfValues = new ArrayList<String>();

for (int i = 0; i < array.length(); i++) {
    JSONObject jboj = array.getJSONObject(i);
    para = new Quote();
    para.pol_status = jboj.getString("Status_Eng");

    JSONArray array1 = jboj.getJSONArray("INFO");

    for (int j = 0; j < array1.length(); j++) {
        JSONObject jObj1 = array1.getJSONObject(j);
        listOfValues.add(jObj1.getString("Val");
    }
}

如果您想要特定的q8,那么它是listOfValues.get(0)

答案 1 :(得分:0)

现在JSON已修复,您发布的代码应该可以正常工作:

for (int j = 0; j < array1.length(); j++) {
    JSONObject jObj1 = array1.getJSONObject(j);
    para.cnum = jObj1.getString("Val").toString();
}

这应该获得Val字段的所有值。如果你不需要所有这些,你可以在循环中检查它们。

答案 2 :(得分:0)

JSONArray array = new JSONArray(response);

JSONObject object = array.getJSONObject(0);


JSONArray infoArray = object.getJSONArray("INFO");
JSONObject objectZero = infoArray.getJSONObject(0);
JSONObject objectOne = infoArray.getJSONObject(1);
String valQ8 = objectZero.getString("Val");
String _89 = objectOne.getString("Val");

答案 3 :(得分:-1)

尝试下面的代码获取字符串信息为

    String info = jboj.getString("INFO");

    JSONArray infoArray = new JSONArray(info);

  for (int infoIndex = 0; infoIndex < infoArray.length();infoIndex++)
                    {

                    JSONObject infoObj = infoArray.getJSONObject(infoIndex );


                        // read the properties here

                        }

答案 4 :(得分:-2)

首先发送同步请求.. 通过查看您给定的数组..有词典信息.. NSURLResponse * response = nil;

NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:nil];

NSDictionary *dictResp = [[NSDictionary alloc]init];


dictResp=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

NSArray * arrProjectDetails = [dictResp objectForKey:@“INFO”];

此数组将包含“Caption”和“val”的所有值。 你可以使用数组索引来获取它。