将 JSON 转换为地图 [英] Convert JSON to Map
问题描述
将 JSON 代码转换为这样的最佳方法是什么:
What is the best way to convert a JSON code as this:
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
在其中一个键是 (field1, field2) 并且这些字段的值是 (value1, value2) 的 Java Map 中.
in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2).
有什么想法吗?我应该为此使用 Json-lib 吗?还是自己写解析器更好?
Any ideas? Should I use Json-lib for that? Or better if I write my own parser?
推荐答案
我希望你是在开玩笑说编写自己的解析器.:-)
I hope you were joking about writing your own parser. :-)
对于这样一个简单的映射,http://json.org(java 部分)中的大多数工具都可以使用.对于其中之一(杰克逊 https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator),你会这样做:
For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:
Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(其中 JSON_SOURCE 是文件、输入流、读取器或 json 内容字符串)
(where JSON_SOURCE is a File, input stream, reader, or json content String)
这篇关于将 JSON 转换为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!