標籤:address ring ted ati 特殊符號 ash art for 知識
■情況
想把代碼中的出現 “ ’等特殊符號時,在他們的前面,轉換時自動加 \ 最後轉換成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 json16 objectMapper.enable(SerializationFeature.INDENT_OUTPUT);17 18 //Define map which will be converted to JSON19 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 JSON26 String mapToJson = objectMapper.writeValueAsString(mapIdPerson);27 System.out.println("1. Convert Map to JSON :");28 System.out.println(mapToJson);29 30 //2. JSON to Map31 //Define Custom Type reference for map type32 TypeReference<Map<String, String>> mapType = new TypeReference<Map<String,String>>() {};33 Map<String,String> jsonToMap = objectMapper.readValue(mapToJson, mapType);34 System.out.println("\n2. Convert JSON to Map :");35 36 // Print map output using Java 837 // lambda expressions38 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 "1811 name=James12 id=00113 age=13
maven的連結如下,你可以選擇自己想要的jar包版本:
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
java知識 特殊符號轉換