解析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}它仍然可以工作.这可行吗?如果是这样,你能给我一些正确方向的推动吗?
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(); }
翻译自:https://stackoverflow.com/questions/6308193/parsing-json-string-in-android