在Android中解析JSON字符串

7

在这里,解析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) 方法中,并返回一个键值对映射。与其他帖子不同的是,我希望解析方法能够为我发送的任何 JSON 字符串创建一个键值对映射。因此,如果我发送了 {"Engine":"v8","Cylinders": 8, "Transmission":"Manual","Gears": 4},它仍然可以工作。这可行吗?如果可以,你能给我一些正确的方向吗?

试试使用Google的GSON库,它非常棒! - james
这不是Android,对吧?或者我漏掉了什么?你在 android 应用程序中使用它似乎完全无关紧要。 - keyser
2个回答

20

在这种情况下,您可以使用JSONObject类的keys方法。 它基本上返回键的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();
}

啊...我甚至没有考虑过那个。我看到的所有示例都使用已知的键...是的,应该可以。我稍后会尝试一下。谢谢! - user631063

1
请注意,Jackson 可以非常简单地反序列化这两个 JSON 示例中的任何一个。
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> values = mapper.readValue(theJsonString, Map.class);

Gson可以以类似的简单方式进行,如果您满意于Map<String, String>而不是Map<String, Object>。目前,对于Map<String, Object>,Gson需要自定义反序列化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接