如何将 JSON 字符串转换为 Map<String, String>与杰克逊 JSON [英] How to convert a JSON string to a Map<String, String> with Jackson JSON
问题描述
我正在尝试做这样的事情,但它不起作用:
I'm trying to do something like this but it doesn't work:
Map<String, String> propertyMap = new HashMap<String, String>();
propertyMap = JacksonUtils.fromJSON(properties, Map.class);
但是 IDE 说:
未检查的赋值Map to Map
这样做的正确方法是什么?我只使用 Jackson 因为这是项目中已经可用的内容,是否有本地 Java 方式来转换 JSON 或从 JSON 转换?
What's the right way to do this? I'm only using Jackson because that's what is already available in the project, is there a native Java way of converting to/from JSON?
在 PHP 中,我会简单地 json_decode($str)
并返回一个数组.我在这里需要基本相同的东西.
In PHP I would simply json_decode($str)
and I'd get back an array. I need basically the same thing here.
推荐答案
[Update Sept 2020] 虽然我多年前在这里的原始答案似乎很有帮助并且仍然获得赞成票,但我现在使用来自 Google 的 GSON 库,我觉得它更直观.
我有以下代码:
public void testJackson() throws IOException {
ObjectMapper mapper = new ObjectMapper();
File from = new File("albumnList.txt");
TypeReference<HashMap<String,Object>> typeRef
= new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> o = mapper.readValue(from, typeRef);
System.out.println("Got " + o);
}
它正在从文件中读取,但是 mapper.readValue()
也将接受一个 InputStream
并且您可以从字符串中获取一个 InputStream
通过使用以下内容:
It's reading from a file, but mapper.readValue()
will also accept an InputStream
and you can obtain an InputStream
from a string by using the following:
new ByteArrayInputStream(astring.getBytes("UTF-8"));
在 我的博客.
这篇关于如何将 JSON 字符串转换为 Map<String, String>与杰克逊 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!