我使用Java,我有一个JSON字符串:

{
"name" : "abc" ,
"email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]
}

然后是我的Java地图:

Map<String, Object> retMap = new HashMap<String, Object>();

我想把所有来自JSONObject的数据存储在那个HashMap中。

有人能为此提供代码吗?我想用org。json库。


当前回答

如果你想要无库版本,这里是与regex的解决方案:

public static HashMap<String, String> jsonStringToMap(String inputJsonString) {
    final String regex = "(?:\\\"|\\')(?<key>[\\w\\d]+)(?:\\\"|\\')(?:\\:\\s*)(?:\\\"|\\')?(?<value>[\\w\\s-]*)(?:\\\"|\\')?";
    HashMap<String, String> map = new HashMap<>();
    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(inputJsonString);

    while (matcher.find()) {
        for (int i = 1; i <= matcher.groupCount(); i++) {
            map.put(matcher.group("key"), matcher.group("value"));
        }
    }
    return map;
}

其他回答

使用Jackson转换:

JSONObject obj = new JSONObject().put("abc", "pqr").put("xyz", 5);

Map<String, Object> map = new ObjectMapper().readValue(obj.toString(), new TypeReference<Map<String, Object>>() {});

你也可以使用Jackson API:

    final String json = "....your json...";
    final ObjectMapper mapper = new ObjectMapper();
    final MapType type = mapper.getTypeFactory().constructMapType(
        Map.class, String.class, Object.class);
    final Map<String, Object> data = mapper.readValue(json, type);

我只用了Gson

HashMap<String, Object> map = new Gson().fromJson(json.toString(), HashMap.class);

您可以使用谷歌gson库转换json对象。

https://code.google.com/p/google-gson/‎

其他图书馆如Jackson也可以使用。

这不会将其转换为映射。但是你可以做任何你想做的事情。

希望这能起作用,试试这个:

import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);

str,你的JSON字符串

就这么简单,如果你想要电子邮件,

String emailIds = response.get("email id").toString();