内容简介:翻译自:https://stackoverflow.com/questions/6308193/parsing-json-string-in-android
解析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
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
How to Build a Billion Dollar App
George Berkowski / Little, Brown Book Group / 2015-4-1 / USD 24.95
Apps have changed the way we communicate, shop, play, interact and travel and their phenomenal popularity has presented possibly the biggest business opportunity in history. In How to Build a Billi......一起来看看 《How to Build a Billion Dollar App》 这本书的介绍吧!
随机密码生成器
多种字符组合密码
html转js在线工具
html转js在线工具