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