Jackson将对象转换成json格式的数据
1 public class Jackson {
2 private ObjectMapper objectMapper = null;
3 private JsonGenerator jsonGenerator = null;
4 private User user = null;
5
6 @Test
7 public void testJackson() {
8 user = new User();
9 user.setId(122);
10 user.setName("打不死的⼩强");
11 user.setDescription("xianqoang");
12
13 objectMapper = new ObjectMapper();
14 try {
15 /*
16 * 第⼀种⽅法:通过objectMapper拿到jsonGenerator(json⽣成器),再通过writeObject(entity)⽅法将对象转换成json
17 */
json转换对象18 jsonGenerator = JsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
19 jsonGenerator.writeObject(user);
20 System.out.println("-------------------------------");
21 /*
22 * 第⼆种⽅法:直接通过ObjectMapper的writeValueAsString(entity)⽅法,最后返回⼀个字符串
23 */
24 String str = objectMapper.writeValueAsString(user);
25 System.out.println(str);
26 } catch (IOException e) {
27 // TODO Auto-generated catch block
28 e.printStackTrace();
29 }
30
31 }
32 @After
33 public void destory() {
34 try {
35 if (jsonGenerator != null) {
36 jsonGenerator.flush();
37 }
38 if (!jsonGenerator.isClosed()) {
39 jsonGenerator.close();
40 }
41 jsonGenerator = null;
42 objectMapper = null;
43 user = null;
();
45 } catch (IOException e) {
46 e.printStackTrace();
47 }
48 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论