如何将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说:
未选中分配
映射到地图<字符串,字符串>
这样做的正确方法是什么?
我只使用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.
推荐答案
我有以下代码:
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屋!