situation
Want to put the code in the "'" and other special symbols, in front of them, the conversion automatically add \ Last converted to JSON
Decide to use Objectmapper this class, first prepare a map, then, map as a parameter, call Objectmapper method, you can automatically add \
Code
1 Importjava.io.IOException;2 ImportJava.util.HashMap;3 ImportJava.util.Map;4 5 Importcom.fasterxml.jackson.core.JsonParseException;6 Importcom.fasterxml.jackson.core.type.TypeReference;7 Importcom.fasterxml.jackson.databind.JsonMappingException;8 ImportCom.fasterxml.jackson.databind.ObjectMapper;9 Importcom.fasterxml.jackson.databind.SerializationFeature;Ten One Public classObjectmapperdemo { A - Public Static voidMain (String args[])throwsjsonparseexception, Jsonmappingexception, IOException { -Objectmapper Objectmapper =NewObjectmapper (); the //Set Pretty printing of JSON - objectmapper.enable (serializationfeature.indent_output); - - //Define map which is converted to JSON +map<string, String>mapidperson =NewHashmap<string, string>(); -Mapidperson.put ("id", "001"); +Mapidperson.put ("name", "James"); AMapidperson.put ("Age", "13"); atMapidperson.put ("Address", "Street \" 18 "); - - //1. Convert Map to JSON -String Maptojson =objectmapper.writevalueasstring (Mapidperson); -System.out.println ("1. Convert Map to JSON: "); - System.out.println (Maptojson); in - //2. JSON to Map to //Define Custom type reference for map type +typereference<map<string, string>> maptype =NewTypereference<map<string,string>>() {}; -Map<string,string> Jsontomap =Objectmapper.readvalue (Maptojson, maptype); theSystem.out.println ("\n2. Convert JSON to Map: "); * $ //Print Map output using Java 8Panax Notoginseng //Lambda Expressions -Jsontomap.foreach (k, v) theSystem.out.println (k + "=" +v)); + } A}
Run Results
1 1. Convert Map to JSON: 2{ 3 "address": "Street \", 4 "name" : "James", 5 "id": "001", 6 "age": " 7} " 8 9 2. Convert JSON to Map:ten address=street "name= James id=001 age=13
Maven links below, you can choose the version of the jar package you want:
Https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
Java Knowledge Special symbol conversion