利用jackson把数据转换成json格式的字符串以及对象中字段的过滤

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;


public class test5 {
	public static void main(String[] args) {
		UserModel u1=new UserModel(1,"w1","1");
		UserModel u2=new UserModel(2,"d2","2");
		UserModel u3=new UserModel(3,"f3","3");
		List list=new ArrayList();
		list.add(u1);
		list.add(u2);
		list.add(u3);
		model2Json(u1);
		
	}
	public static void model2Json(UserModel um){
//实现字段过滤
		ObjectMapper om=new ObjectMapper();
		//不包括
		SimpleFilterProvider fileter = new SimpleFilterProvider();
		fileter.addFilter(
		"testFilter",
		SimpleBeanPropertyFilter.serializeAllExcept(new String[] {
		 "name" }));
		om.setFilters(fileter);
		
		//仅包包括
                 //注意此处要用的注释,testFilter是要注释到实体类上的
//		 SimpleFilterProvider fileter2 = new SimpleFilterProvider();
//		 fileter2.addFilter(
//		 "testFilter",
//		 SimpleBeanPropertyFilter.filterOutAllExcept(new String[] {
//		 "id", "name" }));
//		 om.setFilters(fileter2);
		
		try {
                        //把实体对象转成json格式
			String str=om.writeValueAsString(um);
			System.out.println(str);
			//把json转成实体对象
			UserModel bean=om.readValue(str, UserModel.class);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}

}

 实体类:

写道
@JsonFilter("myFilter")
public class UserModel {
private int id;
private String name;
private String age;
public UserModel(int id,String name,String age){
this.id=id;
this.name=name;
this.age=age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "UserModel [id=" + id + ", name=" + name + ", age=" + age + "]";
}

}

 其他数据格式List ,map用jackson转换json都基本类似,但是像前端传json的时候要假个“()“才可以被eval("("json")")解析. 

 

你可能感兴趣的:(Jackson,解析json)