我有这个JSON字符串:
{
"Data": [
{
"id": "1",
"type": "formal",
"price": "999"
},
{
"id": "2",
"type": "sports",
"price": "799"
}
]
}
JAVA代码
try {
JSONObject parentObject = new JSONObject(result);
dataArray = parentObject.getJSONArray(TAG_ARRAY);
int i=0;
for(i=0;i < dataArray.length();i++) {
JSONObject finalObject = dataArray.getJSONObject(i);
price[i] = String.valueOf(finalObject.getInt(TAG_PRICE));
type[i] = finalObject.getString(TAG_TYPE);
}
} catch (JSONException e) {
e.printStackTrace();
}
我似乎无法获取数据,有什么不对吗?
答案 0 :(得分:0)
使用
try {
JSONObject parentObject = new JSONObject(result);
dataArray = parentObject.optJSONArray("Data");
int i=0;
for(i=0;i < dataArray.length();i++) {
JSONObject finalObject = dataArray.getJSONObject(i);
price[i] = String.valueOf(finalObject.getInt(TAG_PRICE));
type[i] = finalObject.getString(TAG_TYPE);
}
} catch (JSONException e) {
e.printStackTrace();
}
如果您使用JSON进行大量交互,请考虑使用gson或其他专用的json序列化库
答案 1 :(得分:0)
使用此代码。在这里,我使用json-simple作为JSON库。
JSONParser parser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("C:\\sample.json"));
String result = jsonObject.toString();
System.out.println(result);
JSONObject resJsonObject = (JSONObject) parser.parse(result);
JSONArray jsonArray = (JSONArray) jsonObject.get("Data");
for( int i =0; i<jsonArray.size(); i++){
JSONObject childJson = (JSONObject) jsonArray.get(i);
price[i] = (String) childJson.get("price");
type[i] = (String) childJson.get("type");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(price));
System.out.println(Arrays.toString(type));