Java to JSON:
1 package json.jackson; 2 3 import bean.User; 4 import com.fasterxml.jackson.databind.ObjectMapper; 5 6 import java.io.File; 7 import java.util.Map; 8 9 /** 10 * Jackson – Java to JSON 11 * 功能:JSON与Java对象、Map等类型转换,JSON文件的读写等 12 * 依赖包:jackson-databind-2.8.11.1.jar、jackson-core-2.8.10.jar、jackson-annotations-2.8.0.jar 13 * https://github.com/FasterXML/jackson-databind 14 */ 15 public class JavaToJSON { 16 public static void main(String[] ars) throws Exception { 17 User user = new User("tom", 25, "NO.1 street"); 18 ObjectMapper objectMapper = new ObjectMapper(); 19 20 // Java对象转json,也支持bytes 21 String json = objectMapper.writeValueAsString(user); 22 System.out.println("Java对象转json:" + json); 23 24 // json转Java对象 25 User user2 = objectMapper.readValue(json, User.class); 26 System.out.println("json转Java对象" + user2); 27 28 // 读文件 29 String jsonFilePath = "src/main/java/json/jackson/JsonReader.json"; 30 User user3 = objectMapper.readValue(new File(jsonFilePath), User.class); 31 System.out.println("读取JSON文件:" + user3); 32 // 写文件 33 objectMapper.writeValue(new File(jsonFilePath), user3); 34 35 // json转map,也支持List 36 Map map = objectMapper.readValue(json, Map.class); 37 System.out.println("json转map:" + map); 38 39 // map转json字符串,支持所有类型转字符串 40 String json2 = objectMapper.writeValueAsString(map); 41 System.out.println("map转json:" + json2); 42 43 } 44 }
JsonNode:
1 package json.jackson; 2 3 import com.fasterxml.jackson.databind.JsonNode; 4 import com.fasterxml.jackson.databind.ObjectMapper; 5 6 import java.io.File; 7 import java.util.List; 8 9 /** 10 * JsonNode 11 * 处理复杂的JSON,返回多个对象的情况 12 * 从文件中读取复杂的JSON,根据key找到对应value值 13 * 依赖包:jackson-databind-2.8.11.1.jar、jackson-core-2.8.10.jar、jackson-annotations-2.8.0.jar 14 * https://github.com/FasterXML/jackson-databind 15 */ 16 public class JSONTreeDemo { 17 public static void main(String[] ars) throws Exception { 18 ObjectMapper objectMapper = new ObjectMapper(); 19 String jsonFilePath = "src/main/java/json/jackson/Json2.json"; 20 // 以树形态支持多对象的情况:支持读取多种类型 21 JsonNode jsonNode = objectMapper.readTree(new File(jsonFilePath)); 22 System.out.println("jsonNode:" + jsonNode); 23 // 根据key查询多个值,返回list 24 List<JsonNode> list = jsonNode.findValues("name"); 25 System.out.println("Values:" + list); 26 27 // 根据key查询单个值 28 String channel = jsonNode.get("channel").asText(); 29 System.out.println("查询channel的值:" + channel); 30 } 31 }