我试着做一些这样的事情,但它不起作用:
Map<String, String> propertyMap = new HashMap<String, String>();
propertyMap = JacksonUtils.fromJSON(properties, Map.class);
但是IDE说:
未检查映射到映射<字符串,字符串>
正确的做法是什么?
我只使用杰克逊,因为这是什么已经在项目中,有一个本地Java的方式转换到/从JSON?
在PHP中,我将简单地json_decode($str),我将返回一个数组。我在这里也需要同样的东西。
[更新2020年9月]虽然我多年前在这里的原始答案似乎很有帮助,而且仍然得到了点赞,但我现在使用谷歌的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:
new ByteArrayInputStream(astring.getBytes("UTF-8"));
在我的博客上有更多关于绘图仪的解释。
你得到的警告是由编译器完成的,而不是由库(或实用程序方法)。
直接使用Jackson的最简单方法是:
HashMap<String,Object> props;
// src is a File, InputStream, String or such
props = new ObjectMapper().readValue(src, new TypeReference<HashMap<String,Object>>() {});
// or:
props = (HashMap<String,Object>) new ObjectMapper().readValue(src, HashMap.class);
// or even just:
@SuppressWarnings("unchecked") // suppresses typed/untype mismatch warnings, which is harmless
props = new ObjectMapper().readValue(src, HashMap.class);
你调用的实用工具方法可能会做类似的事情。