当我JSONObject jsonObj = new JSONObject(jsonStr);
时
我输入catch因为我的json不是数组。
我怎样才能获得这种格式?
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:8080/PFA/crimes";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String day_week = c.getString("day_week");
String naturecode = c.getString("naturecode");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("day_week", day_week);
contact.put("naturecode", naturecode);
// adding contact to contact list
List.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
JSON:
{
"crime": {
"compnos": "zerezrerzerezzr",
"day_week": "rtkeertoeirtj ,ertkierj",
"domestic": "false",
"fromdate": "ekrjtner",
"id": "1",
"location": "etritkjrtoijty",
"main_crimecode": "oijereriotjeroi",
"month": "455",
"naturecode": "zetzeeztet",
"reportingarea": "58",
"reptdistrict": "zorigjrgoijtoi",
"shift": "rektenrloj",
"shooting": "true",
"streetname": "kjrtnerkj",
"ucrpart": "irtjeroitejroirj",
"weapontype": "kejfnergkrtnh",
"x": "11",
"xstreetname": "zekjrnetk",
"y": "11",
"year": "45"
}
}
答案 0 :(得分:1)
试试这个:
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonMetaObject = jsonMasterObject.getJSONObject("crime");
而不是
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
因为你在犯罪的关键中得到jsonObject而不是JsonArray。
答案 1 :(得分:1)
JsonObject crime = jsonObj.getJsonObject(&#34; crime&#34;);
JsonObject compnos = crime.getJsonObject(&#34; compnos&#34;);
。 .. ...
你的json值中没有jsonArray。放弃获取jsonArray。