java 在android中解析JSON字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6308193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:18:53  来源:igfitidea点击:

Parsing JSON string in android

javaandroidjsonparsing

提问by Cristian

Parsing JSON seems like it is a pretty common topic of discussion on here. I have looked around and still have not found what I am looking for. Here is my code for my HttpClient

解析 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);

I am using a HttpClient to send a JSON request to a server. The server then returns a response in JSON. This works great. Now here is where I am running into trouble. I am receiving an HttpEntity from the server. I am then turning that into a string which looks like this. {"Make":"Ford","Year": 1975, "Model":"Mustang"}I want to be able to send this string to my parseJSON(String jString)method and it return a key value map. Where I feel this differs from other posts is that I want the parse method to be able to create a key value map for any JSON string I send it. So if I sent it {"Engine":"v8","Cylinders": 8, "Transmission":"Manual","Gears": 4}it would still work. Is this doable? And if so, could you give me some nudges in the right direction?

我正在使用 HttpClient 向服务器发送 JSON 请求。然后服务器以 JSON 格式返回响应。这很好用。现在这是我遇到麻烦的地方。我正在从服务器接收一个 HttpEntity。然后我把它变成一个看起来像这样的字符串。{"Make":"Ford","Year": 1975, "Model":"Mustang"}我希望能够将此字符串发送到我的parseJSON(String jString)方法并返回一个键值映射。我觉得这与其他帖子的不同之处在于我希望 parse 方法能够为我发送的任何 JSON 字符串创建一个键值映射。所以如果我发送它{"Engine":"v8","Cylinders": 8, "Transmission":"Manual","Gears": 4}仍然有效。这是可行的吗?如果是这样,你能给我一些正确方向的推动吗?

回答by Cristian

In this case you can use the keysmethod of the JSONObjectclass. It will basically returns an Iteratorof the keys, that you can then iterate to get and put the values in a map:

在这种情况下,您可以使用类的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();
}

回答by Programmer Bruce

Note that Hymansoncan deserialize either of the two JSON examples very simply.

请注意,Hymanson可以非常简单地反序列化两个 JSON 示例中的任何一个。

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> values = mapper.readValue(theJsonString, Map.class);

Gsoncan do it similarly simply if you're satisfied with a Map<String, String>, instead of a Map<String, Object>. Currently, Gson would need custom deserialization for a Map<String, Object>.

如果您对 aMap<String, String>而不是 a感到满意,Gson可以类似地做到这一点Map<String, Object>。目前,Gson 需要自定义反序列化Map<String, Object>.