■情况
想把代码中的出现 “ ’等特殊符号时,在他们的前面,转换时自动加 最后转换成json
决定用ObjectMapper这个类,先准备一个Map,之后,map作为一个参数,调用ObjectMapper的方法,就能在转换时自动加上
■代码
1 import java.io.IOException; 2 import java.util.HashMap; 3 import java.util.Map; 4 5 import com.fasterxml.jackson.core.JsonParseException; 6 import com.fasterxml.jackson.core.type.TypeReference; 7 import com.fasterxml.jackson.databind.JsonMappingException; 8 import com.fasterxml.jackson.databind.ObjectMapper; 9 import com.fasterxml.jackson.databind.SerializationFeature; 10 11 public class ObjectMapperDemo { 12 13 public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException { 14 ObjectMapper objectMapper = new ObjectMapper(); 15 //Set pretty printing of json 16 objectMapper.enable(SerializationFeature.INDENT_OUTPUT); 17 18 //Define map which will be converted to JSON 19 Map<String, String>mapIdPerson = new HashMap<String, String>(); 20 mapIdPerson.put("id", "001"); 21 mapIdPerson.put("name", "James"); 22 mapIdPerson.put("age", "13"); 23 mapIdPerson.put("address", "street "18"); 24 25 //1. Convert Map to JSON 26 String mapToJson = objectMapper.writeValueAsString(mapIdPerson); 27 System.out.println("1. Convert Map to JSON :"); 28 System.out.println(mapToJson); 29 30 //2. JSON to Map 31 //Define Custom Type reference for map type 32 TypeReference<Map<String, String>> mapType = new TypeReference<Map<String,String>>() {}; 33 Map<String,String> jsonToMap = objectMapper.readValue(mapToJson, mapType); 34 System.out.println(" 2. Convert JSON to Map :"); 35 36 // Print map output using Java 8 37 // lambda expressions 38 jsonToMap.forEach((k, v) -> 39 System.out.println(k + "=" + v)); 40 } 41 }
■运行结果
1 1. Convert Map to JSON : 2 { 3 "address" : "street "18", 4 "name" : "James", 5 "id" : "001", 6 "age" : "13" 7 } 8 9 2. Convert JSON to Map : 10 address=street "18 11 name=James 12 id=001 13 age=13
maven的链接如下,你可以选择自己想要的jar包版本:
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind