解析json的常用方法

Jackson 操作json数据

1.jackson的相关依赖

Jackson有1.x系列和2.x系列,2.x系列有3个jar包需要下载:
        jackson-core-2.2.3.jar(核心jar包)
        jackson-annotations-2.2.3.jar(该包提供Json注解支持)
        jackson-databind-2.2.3.jar

//jackson的相关依赖,只需要导入这个jar

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>

2.常用的序列化和反序列化的方法

public class JacksonTest {
	
	static final ObjectMapper mapper = new ObjectMapper();
	
	public static void main(String[] args) throws ParseException, Exception {
		User user = new User();
        user.setName("zhangsan");
        user.setPassword("12892ss");
        user.setAge(20);
        user.setId(1);

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        user.setBirthday(dateformat.parse("1996-10-01"));
        
        List<Img> imgs = new ArrayList<Img>();
        for (int i = 0; i < 2; i++) {
        	Img img = new Img();
        	img.setExt("jpg"+i);
        	img.setUrl("www.baidu.com:"+i*10);
        	imgs.add(img);
		}
        user.setImgs(imgs);
        
        /**
         * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
         * ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
         * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
         * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
         * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
         * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。
         */
        
          
        /**
         	* 对象转json串,json序列化
         */
        
        //User类转JSON
        //输出结果:{"name":"zhangsan","age":20,"birthday":844099200000,"email":"[email protected]"}
        String json = mapper.writeValueAsString(user);
        System.out.println(json);

        //Java集合转JSON
        //输出结果:[{"name":"zhangsan","age":20,"birthday":844099200000,"email":"[email protected]"}]
        List<User> users = new ArrayList<User>();
        users.add(user);
        String jsonlist = mapper.writeValueAsString(users);
        System.out.println(jsonlist);
  
		User u = mapper.readValue(json, User.class);
		System.out.println(u);
		
//		List<User> beanList = mapper.readValue(jsonlist, new TypeReference<List<User>>(){});
		List<User> beanList = mapper.readValue(jsonlist, mapper.getTypeFactory().constructCollectionType(List.class, User.class));
		System.out.println(beanList.get(0).getPassword());
		
		
		System.out.println("--------");
		
		JsonNode node = mapper.readTree(json);
		//JsonNode jsonNode = node.get("imgs");
		String name = node.get("name").asText();
		int age = node.get("age").asInt();
		ArrayNode rows = (ArrayNode) node.get("imgs");//专程json数组
		for (JsonNode js : rows) {
			String url = js.get("url").asText();
		}
		System.out.println(node.get("imgs"));
		
	    List<Img> items = mapper.readValue(node.get("imgs").toString(), mapper.getTypeFactory()
                .constructCollectionType(List.class, Img.class));
	    System.out.println(items);
		
	}

3.jackson 中常用注解

Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解。
	@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。
	@JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。
	@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")。
	@JsonInclude(Include.NON_NULL) 不为空的时候显示,或者其他配置,根据枚举选择

猜你喜欢

转载自blog.csdn.net/weixin_37598682/article/details/81174736