Java to JSON:
package json.jackson; import bean.User;
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File;
import java.util.Map; /**
* Jackson – Java to JSON
* 功能:JSON与Java对象、Map等类型转换,JSON文件的读写等
* 依赖包:jackson-databind-2.8.11.1.jar、jackson-core-2.8.10.jar、jackson-annotations-2.8.0.jar
* https://github.com/FasterXML/jackson-databind
*/
public class JavaToJSON {
public static void main(String[] ars) throws Exception {
User user = new User("tom", 25, "NO.1 street");
ObjectMapper objectMapper = new ObjectMapper(); // Java对象转json,也支持bytes
String json = objectMapper.writeValueAsString(user);
System.out.println("Java对象转json:" + json); // json转Java对象
User user2 = objectMapper.readValue(json, User.class);
System.out.println("json转Java对象" + user2); // 读文件
String jsonFilePath = "src/main/java/json/jackson/JsonReader.json";
User user3 = objectMapper.readValue(new File(jsonFilePath), User.class);
System.out.println("读取JSON文件:" + user3);
// 写文件
objectMapper.writeValue(new File(jsonFilePath), user3); // json转map,也支持List
Map map = objectMapper.readValue(json, Map.class);
System.out.println("json转map:" + map); // map转json字符串,支持所有类型转字符串
String json2 = objectMapper.writeValueAsString(map);
System.out.println("map转json:" + json2); }
}
JsonNode:
package json.jackson; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File;
import java.util.List; /**
* JsonNode
* 处理复杂的JSON,返回多个对象的情况
* 从文件中读取复杂的JSON,根据key找到对应value值
* 依赖包:jackson-databind-2.8.11.1.jar、jackson-core-2.8.10.jar、jackson-annotations-2.8.0.jar
* https://github.com/FasterXML/jackson-databind
*/
public class JSONTreeDemo {
public static void main(String[] ars) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String jsonFilePath = "src/main/java/json/jackson/Json2.json";
// 以树形态支持多对象的情况:支持读取多种类型
JsonNode jsonNode = objectMapper.readTree(new File(jsonFilePath));
System.out.println("jsonNode:" + jsonNode);
// 根据key查询多个值,返回list
List<JsonNode> list = jsonNode.findValues("name");
System.out.println("Values:" + list); // 根据key查询单个值
String channel = jsonNode.get("channel").asText();
System.out.println("查询channel的值:" + channel);
}
}