Json

fastjson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class FastjsonTest {

// 将User对象转换成json
@Test
public void test1() {
User user = new User();
user.setAge(20);
user.setBirthday(new Date());
user.setId(1);
user.setName("tom");


// 转换成json
String json = JSONObject.toJSONString(user);
System.out.println(json);
User user1 = JSON.parseObject(json, User.class);
System.out.println(user1.getName());
// {"age":20,"birthday":1479455891302,"id":1,"name":"tom"}
}

// 将List<User>转换成json
@Test
public void test2() {
User u1 = new User();
u1.setAge(20);
u1.setBirthday(new Date());
u1.setId(1);
u1.setName("tom");

User u2 = new User();
u2.setAge(20);
u2.setBirthday(new Date());
u2.setId(1);
u2.setName("fox");
List<User> users = new ArrayList<User>();
users.add(u1);
users.add(u2);

String json = JSONArray.toJSONString(users);
System.out.println(json);

List<User> users1 = JSON.parseArray(json, User.class);
System.out.println(users1.get(0).getName());
}
}

jackson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class JacksonTest {

// 将Product转换成json
@Test
public void test1() throws JsonGenerationException, JsonMappingException, IOException {
Product p = new Product();
p.setId(1);
p.setName("电视机");
p.setPrice(2000);
p.setReleaseDate(new Date());

ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); // 设置日期格式化器
String json = mapper.writeValueAsString(p);
System.out.println(json);
Product p1 = mapper.readValue(json, Product.class);
System.out.println(p1.getName());
}

// 将List<Product>转换成json
@Test
public void test2() throws JsonGenerationException, JsonMappingException, IOException {
Product p1 = new Product();
p1.setId(1);
p1.setName("电视机");
p1.setPrice(2000);

Product p2 = new Product();
p2.setId(2);
p2.setName("电冰箱");
p2.setPrice(3000);

List<Product> ps = new ArrayList<Product>();
ps.add(p1);
ps.add(p2);

ObjectMapper mapper = new ObjectMapper();

// 处理过滤属性
FilterProvider fp = new SimpleFilterProvider().addFilter("productFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("id", "name")); //只包含id与name

//FilterProvider fp = new SimpleFilterProvider().addFilter("productFilter",
//SimpleBeanPropertyFilter.serializeAllExcept("id", "name")); //不包含id与name

mapper.setFilters(fp);

String json = mapper.writeValueAsString(ps);
System.out.println(json);
JavaType javaType = getCollectionType(ArrayList.class, Product.class);
List<Product> ps1 = (List<Product>) mapper.readValue(json, javaType);
System.out.println(ps1.get(0).getName());
}


public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
ObjectMapper mapper = new ObjectMapper();
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
}