开发者社区> 问答> 正文

JSON转util.Map,请问在2.x中应该怎么转换

2.x中如何将JSON转util.Map 在1.x中JSON转util.Map如下:

//JSON格式: {"a":"111","b":"222","c":"333"} JSONObject jsonConf = ...; Map<String, String> conf = jsonConf.toJavaObject(new TypeReference<Map<String, String>>() {});

请问在2.x中应该怎么转换,没看到相应的兼容方法

原提问者GitHub用户hujian0923

展开
收起
大圣东游 2023-04-21 12:03:26 234 0
2 条回答
写回答
取消 提交回答
  • 值得去的地方都没有捷径

    在 GPT-3.5 中,建议您使用 jackson 库来将 JSON 转换为 Map。以下是一个示例:

    import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper;

    public class Example { public static void main(String[] args) throws JsonProcessingException { // JSON 字符串 String jsonString = "{"a":"111","b":"222","c":"333"}";

        // 创建一个 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();
    
        // 将 JSON 字符串转换为 Map
        Map<String, String> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, String>>() {});
    
        // 输出 Map 的内容
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
    

    } 在这个例子中,我们首先使用 ObjectMapper 类创建了一个对象。然后,我们使用 readValue() 方法将 JSON 字符串转换为 Map,并指定转换类型为 Map<String, String>。最后,我们遍历 Map 的每个元素,并将其输出到控制台。

    2023-04-21 21:17:05
    赞同 展开评论 打赏
  •     String str = "{}";
        {
            JSONReader jsonReader = JSONReader.of(str);
            jsonReader.getContext().setObjectSupplier(HashMap::new);
            assertEquals(HashMap.class, jsonReader.readObject().getClass());
        }
        {
            JSONReader jsonReader = JSONReader.of(str);
            jsonReader.getContext().setObjectSupplier(HashMap::new);
            assertEquals(HashMap.class, jsonReader.read(Object.class).getClass());
        }
        {
            JSONReader jsonReader = JSONReader.of(str);
            jsonReader.getContext().setObjectSupplier(HashMap::new);
            assertEquals(HashMap.class, jsonReader.read(Map.class).getClass());
        }
    

    2.0.5的如上例子中,可以配置ObjectSupplier,你可以自己决定用哪个Map

    https://github.com/alibaba/fastjson2/releases/tag/2.0.6 问题已经修复,请用新版本

    原回答者GitHub用户wenshao

    2023-04-21 14:50:28
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载