Java 仅使用字符串和值解析 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4407532/
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
Parse JSON object with string and value only
提问by Edy Cu
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. And because the string json will always different one with another. ex:
但是我如何使用这种 JSON 格式解析映射,只使用字符串和值最小格式使用循环映射到 java 映射集合。并且因为字符串 json 总是与另一个不同。前任:
{"1":"sql", "2":"android", "3":"mvc"}
Thank
谢谢
采纳答案by dogbane
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);
}
回答by Buhake Sindi
My pseudocodeexample 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;