Home >Java >javaTutorial >How to Efficiently Convert JSON to a Java Map?
Converting JSON to Maps in Java
Problem Statement:
Tasked with converting a given JSON structure into a Java Map where the keys are tuples of fields and the values are corresponding tuple of values, the question arises: Which approach should be adopted? Should a third-party library like Json-lib be utilized, or should a custom parser be developed?
Resolution:
It's generally inadvisable to create your own parser for such a straightforward mapping. Instead, leveraging existing libraries from http://json.org's Java section is recommended.
Implementation with Jackson:
Jackson, available at https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator, provides an efficient solution:
Map<String,Object> result = new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
where JSON_SOURCE can represent a File, input stream, reader, or a String containing the JSON content.
The above is the detailed content of How to Efficiently Convert JSON to a Java Map?. For more information, please follow other related articles on the PHP Chinese website!