java知識 特殊符號轉換

來源:互聯網
上載者:User

標籤: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知識 特殊符號轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.