简体   繁体   English

仅使用字符串和值解析JSON对象

[英]Parse JSON object with string and value only

I have problem when trying to parse with minimum value to map in Android. 尝试使用最小值解析以在Android中映射时,我遇到了问题。

There some sample JSON format with more information ex: 有一些示例JSON格式,其中包含更多信息:

[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]

This that example most common to use and easy to use just use getString("id") or getValue("name") . 这个使用最常见且易于使用的示例只使用getString("id")getValue("name")

But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. 但是我如何解析使用这种JSON格式进行映射,只使用字符串和值最小格式到使用循环的java map集合。 And because the string json will always different one with another. 因为字符串json总是彼此不同。 ex: 例如:

{"1":"sql", "2":"android", "3":"mvc"}

Thank 谢谢

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below: 您需要获取所有键的列表,循环遍历它们并将它们添加到地图中,如下例所示:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

My pseudocode example will be as follows: 我的伪代码示例如下:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM