Java Parser Json作为数组多维

时间:2015-12-23 10:16:15

标签: java arrays json

解析Json时遇到了一些麻烦。这是我的Json:

{
  "responseHeader": {
    "status": 0,
    "QTime": 1
  },
  "response": {
    "numFound": 3447,
    "start": 0,
    "docs": [
      {
        "sku": "5848-05855-0064",
        "skus": [
          "5848-05855-0064",
          "5848-05855-0064-5340"
        ]
      },
      {
        "sku": "5848-05849-0059",
        "skus": [
          "5848-05849-0059",
          "5848-05849-0059-5340"
        ]
      }
    ]
  },
  "facet_counts": {
    "facet_queries": {},
    "facet_fields": {},
    "facet_dates": {},
    "facet_ranges": {}
  }
}
    ]
  },
  "facet_counts": {
    "facet_queries": {},
    "facet_fields": {},
    "facet_dates": {},
    "facet_ranges": {}
  }
}

我可以使用以下代码获得“sku”值:

String jsonData = responses.body().string();

JSONObject Jobject = new JSONObject(jsonData);      
Jobject = (JSONObject) Jobject.get("response");     
Object skuValues = Jobject.get("docs");

JSONArray jArray = (JSONArray) skuValues;       
JSONObject skuConfig = jArray.getJSONObject(1);
String sku = skuConfig.getString("sku");

但我无法获得“skus”值。有人可以指导我如何从JSON中获得“skus”值吗?

3 个答案:

答案 0 :(得分:1)

要检索skus,您可以执行以下操作: -

JSONArray skus = skuConfig.getJSONArray("skus");

要获得值,您可以执行以下操作: -

skus1 = skus.getString(0);

答案 1 :(得分:0)

以下为我工作:

Gson gson = new Gson();
Map fromJson = gson.fromJson("{  \"responseHeader\": {    \"status\": 0,    \"QTime\": 1  },  \"response\": {    \"numFound\": 3447,    \"start\": 0,    \"docs\": [      {        \"sku\": \"5848-05855-0064\",        \"skus\": [          \"5848-05855-0064\",          \"5848-05855-0064-5340\"        ]      },      {        \"sku\": \"5848-05849-0059\",        \"skus\": [          \"5848-05849-0059\",          \"5848-05849-0059-5340\"        ]      }    ]  },  \"facet_counts\": {    \"facet_queries\": {},    \"facet_fields\": {},    \"facet_dates\": {},    \"facet_ranges\": {}  }}", Map.class);
JSONObject Jobject = new JSONObject(fromJson);      
StringMap Jobject1 = (StringMap) Jobject.get("response");     
Object skuValues = Jobject1.get("docs");

ArrayList jArray = (ArrayList) skuValues;       
StringMap skuConfig = (StringMap) jArray.get(0);
System.out.println(skuConfig);
System.out.println(skuConfig.get("skus"));

答案 2 :(得分:0)

第1点:您的示例JSON错误,请使用以下链接验证并格式化JSON https://jsonformatter.curiousconcept.com/

第2点:使用以下代码

JSONObject Jobject;
        Jobject = new JSONObject(jsonData);
        Jobject = (JSONObject) Jobject.get("response");
        JSONArray docs = Jobject.getJSONArray("docs");

        for (int i = 0; i < docs.length(); i++) {
            JSONObject skuDoc = docs.getJSONObject(i);
            String skuValue = skuDoc.optString("sku");
            JSONArray skusArr = skuDoc.getJSONArray("skus");
            System.out.println(skusArr);
        }