需要jar包:jackson-core-2.6.0.jar,jackson-databind-2.6.0.jar,jackson-annotations-2.6.0.jar
- JSON String to Map
package com.inspur.trc.util;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Json2Map {
public static void main(String[] args) {
String json = "{\"name\":\"zitong\", \"age\":\"26\"}";
Map<String, String> map = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
try{
map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){});
System.out.println(map);
}catch(Exception e){
e.printStackTrace();
}
}
}
运行结果:
{age=26, name=zitong}
- Map to JSON String
package com.inspur.trc.util;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Map2Json {
public static void main(String[] args){
try{
ObjectMapper mapper = new ObjectMapper();
String json = "";
Map<String, String> map = new HashMap<String,String>();
map.put("name", "zitong");
map.put("age", "26");
json = mapper.writeValueAsString(map);
System.out.println(json);
}catch(Exception e){
e.printStackTrace();
}
}
}
运行结果:
{"age":"26","name":"zitong"}