解析JSON似乎是这里讨论的一个相当普遍的话题。我环顾四周,但仍然找不到我想要的东西。这是我的HttpClient的代码
public class CreateJsonRequest { public static String SendJsonRequest(String URL, Map<String,Object> params){ try{ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(URL); JSONObject holder = new JSONObject(); for (Map.Entry<String, Object> m : params.entrySet()){ try { holder.put(m.getKey(), m.getValue()); } catch (JSONException e) { Log.e("Hmmmm", "JSONException : "+e); } } StringEntity se; se = new StringEntity(holder.toString()); httpPost.setEntity(se); httpPost.setHeader("Accept", "text/json"); httpPost.setHeader("Content-type", "text/json"); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if(entity != null){ final JSONObject respObject = new JSONObject(EntityUtils.toString(entity)); String result = respObject.toString(); parseJSON(result);
我正在使用HttpClient将JSON请求发送到服务器。然后,服务器以JSON返回响应。这很好。现在这是我遇到麻烦的地方。我从服务器接收到HttpEntity。然后,我将其变成看起来像这样的字符串。{"Make":"Ford","Year": 1975, "Model":"Mustang"} 我希望能够将此字符串发送到我的parseJSON(String jString)方法,并且它返回键值映射。我觉得这与其他文章不同的地方是,我希望parse方法能够为我发送的任何JSON字符串创建键值映射。因此,如果我发送了{"Engine":"v8","Cylinders": 8, "Transmission":"Manual","Gears": 4}它,仍然可以使用。这可行吗?如果是这样,您能给我一些正确的方向吗?
{"Make":"Ford","Year": 1975, "Model":"Mustang"}
parseJSON(String jString)
{"Engine":"v8","Cylinders": 8, "Transmission":"Manual","Gears": 4}
在这种情况下,您可以使用类的keys方法JSONObject。它将基本上返回Iterator键中的一个,然后您可以迭代该键以将值放入地图中:
keys
JSONObject
Iterator
try { JSONObject jsonObject = new JSONObject(theJsonString); Iterator keys = jsonObject.keys(); Map<String, String> map = new HashMap<String, String>(); while (keys.hasNext()) { String key = (String) keys.next(); map.put(key, jsonObject.getString(key)); } System.out.println(map);// this map will contain your json stuff } catch (JSONException e) { e.printStackTrace(); }