1、如果任务下来了,并且给定了你指定格式的JSON数据类型,那么就要想法封装成此种JSON格式的数据类型,方便其他成员进行调用,那么是如何进行封装的呢,这里简单研究一下子。

2、如果文档指定的封装类型是下面,这样格式的,应该如何进行封装呢?

 1 { 
 2     "code": 0, 
 3     "msg": "success", 
 4     "data": { 
 5         "id": 2, 
 6         "account": "张三", 
 7         "cname": "张三", 
 8         "sex": "男", 
 9         "password": "123456", 
10         "identity": "415555555555555552", 
11         "telephone": "15255555555", 
12         "address": "河南省商丘市", 
13         "birthday": "1999-06-15", 
14         "identification": "1" 
15     } 
16 }

2.1、那么可以封装一个工具类,定义三个参数,分别是code、msg、data(这里使用的是Object类型的,你也可以设置成泛型的,看自己的喜好了)。然后创建几个调用成功,失败,或者自己构建一个方法,将参数传递进去即可。

  1 package com.bie.demo.utils; 
  2  
  3 import com.fasterxml.jackson.databind.JsonNode; 
  4 import com.fasterxml.jackson.databind.ObjectMapper; 
  5  
  6 import java.io.Serializable; 
  7 import java.util.List; 
  8  
  9 /** 
 10  * @ProjectName: nationalpolicy 
 11  * @Package: com.feixian.nationalpolicy.utils 
 12  * @ClassName: NationalPolicyResult 
 13  * @Author: biehl 
 14  * @Description: ${description} 
 15  * @Date: 2020/2/28 10:40 
 16  * @Version: 1.0 
 17  */ 
 18 public class NationalPolicyResult implements Serializable { 
 19  
 20     /** 
 21      * 
 22      */ 
 23     private static final long serialVersionUID = 1L; 
 24  
 25     // 定义jackson对象 
 26     private static final ObjectMapper MAPPER = new ObjectMapper(); 
 27  
 28     // 返回标记,成功标记为0,失败为1 
 29     private Integer code; 
 30  
 31     // 返回消息 
 32     private String msg; 
 33  
 34     // 返回中的数据 
 35     private Object data; 
 36  
 37     /** 
 38      * 1、成功返回调用的方法 
 39      * 
 40      * @param data 
 41      * @return 
 42      */ 
 43     public static NationalPolicyResult success(Object data) { 
 44         return new NationalPolicyResult(data); 
 45     } 
 46  
 47     /** 
 48      * 2、成功返回调用的方法,重载方法 
 49      * 
 50      * @return 
 51      */ 
 52     public static NationalPolicyResult success() { 
 53         return new NationalPolicyResult(null); 
 54     } 
 55  
 56  
 57     /** 
 58      * 3、传入封装的数据,返回标记和返回信息进行默认 
 59      * 
 60      * @param data 
 61      */ 
 62     public NationalPolicyResult(Object data) { 
 63         this.code = 0; 
 64         this.msg = "success"; 
 65         this.data = data; 
 66     } 
 67  
 68     /** 
 69      * 4、无参的构造方法 
 70      */ 
 71     public NationalPolicyResult() { 
 72  
 73     } 
 74  
 75     /** 
 76      * 5、自己构建一个方法,调用构造方法,返回自己封装的状态,返回信息,和封装的数据信息 
 77      * 
 78      * @param code 
 79      * @param msg 
 80      * @param data 
 81      * @return 
 82      */ 
 83     public static NationalPolicyResult build(Integer code, String msg, Object data) { 
 84         return new NationalPolicyResult(code, msg, data); 
 85     } 
 86  
 87     /** 
 88      * 6、自己构建一个方法,重载,调用构造方法,默认封装的数据信息为null 
 89      * 
 90      * @param code 
 91      * @param msg 
 92      * @return 
 93      */ 
 94     public static NationalPolicyResult build(Integer code, String msg) { 
 95         return new NationalPolicyResult(code, msg, null); 
 96     } 
 97  
 98     /** 
 99      * 7、可以传入封装的数据,和封装的信息,失败或者成功 
100      * 
101      * @param data 
102      * @param msg 
103      */ 
104     public NationalPolicyResult(Object data, String msg) { 
105         this.code = 0; 
106         this.msg = msg; 
107         this.data = data; 
108     } 
109  
110  
111     /** 
112      * 8、含参的构造方法 
113      * 
114      * @param code 
115      * @param msg 
116      * @param data 
117      */ 
118     public NationalPolicyResult(Integer code, String msg, Object data) { 
119         this.code = code; 
120         this.msg = msg; 
121         this.data = data; 
122     } 
123  
124     public Integer getCode() { 
125         return code; 
126     } 
127  
128     public void setCode(Integer code) { 
129         this.code = code; 
130     } 
131  
132     public String getMsg() { 
133         return msg; 
134     } 
135  
136     public void setMsg(String msg) { 
137         this.msg = msg; 
138     } 
139  
140     public Object getData() { 
141         return data; 
142     } 
143  
144     public void setData(Object data) { 
145         this.data = data; 
146     } 
147  
148  
149     /** 
150      * 将json结果集转化为NationalPolicyResult对象 
151      * 
152      * @param jsonData json数据 
153      * @param clazz    NationalPolicyResult中的object类型 
154      * @return 
155      */ 
156     public static NationalPolicyResult formatToPojo(String jsonData, Class<?> clazz) { 
157         try { 
158             if (clazz == null) { 
159                 return MAPPER.readValue(jsonData, NationalPolicyResult.class); 
160             } 
161             JsonNode jsonNode = MAPPER.readTree(jsonData); 
162             JsonNode data = jsonNode.get("data"); 
163             Object obj = null; 
164             if (clazz != null) { 
165                 if (data.isObject()) { 
166                     obj = MAPPER.readValue(data.traverse(), clazz); 
167                 } else if (data.isTextual()) { 
168                     obj = MAPPER.readValue(data.asText(), clazz); 
169                 } 
170             } 
171             return build(jsonNode.get("code").intValue(), jsonNode.get("msg").asText(), obj); 
172         } catch (Exception e) { 
173             return null; 
174         } 
175     } 
176  
177     /** 
178      * 没有object对象的转化 
179      * 
180      * @param json 
181      * @return 
182      */ 
183     public static NationalPolicyResult format(String json) { 
184         try { 
185             return MAPPER.readValue(json, NationalPolicyResult.class); 
186         } catch (Exception e) { 
187             e.printStackTrace(); 
188         } 
189         return null; 
190     } 
191  
192     /** 
193      * Object是集合转化 
194      * 
195      * @param jsonData json数据 
196      * @param clazz    集合中的类型 
197      * @return 
198      */ 
199     public static NationalPolicyResult formatToList(String jsonData, Class<?> clazz) { 
200         try { 
201             JsonNode jsonNode = MAPPER.readTree(jsonData); 
202             JsonNode data = jsonNode.get("data"); 
203             Object obj = null; 
204             if (data.isArray() && data.size() > 0) { 
205                 obj = MAPPER.readValue(data.traverse(), 
206                         MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)); 
207             } 
208             return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); 
209         } catch (Exception e) { 
210             return null; 
211         } 
212     } 
213  
214 }

2.2、将查询返回的结果进行封装返回,如果失败了,或者成功了,如何进行调用。如下所示:

 1 package com.bie.demo.controller; 
 2  
 3 import com.bie.demo.po.CustomerInfo; 
 4 import com.bie.demo.service.CustomerInfoService; 
 5 import com.bie.demo.utils.NationalPolicyResult; 
 6 import org.springframework.beans.factory.annotation.Autowired; 
 7 import org.springframework.stereotype.Controller; 
 8 import org.springframework.web.bind.annotation.RequestMapping; 
 9 import org.springframework.web.bind.annotation.RequestParam; 
10 import org.springframework.web.bind.annotation.ResponseBody; 
11  
12 /** 
13  * 
14  */ 
15 @Controller 
16 @RequestMapping(value = "/customerInfo") 
17 public class CustomerInfoController { 
18  
19     @Autowired 
20     private CustomerInfoService customerInfoService; 
21  
22     @RequestMapping(value = "/selectCustomerInfoById") 
23     @ResponseBody 
24     public NationalPolicyResult selectCustomerInfoById(@RequestParam(value = "id") int id) { 
25         CustomerInfo customerInfo = customerInfoService.selectCustomerInfoById(id); 
26         NationalPolicyResult nationalPolicyResult = new NationalPolicyResult(); 
27         NationalPolicyResult result = null; 
28         if (customerInfo != null) { 
29             result = nationalPolicyResult.success(customerInfo); 
30         } else { 
31             result = nationalPolicyResult.build(1, "失败了......."); 
32         } 
33         return result; 
34     } 
35  
36  
37 }

2.3、页面调用一下,看看是否正确的返回结果。

使用json在线解析,查看是否是正确的json格式。

3、如果文档指定的封装类型是下面,这样格式的,应该如何进行封装呢?

 1 { 
 2     "code": 0, 
 3     "msg": "success", 
 4     "data": { 
 5         "records": [{ 
 6             "id": 1, 
 7             "account": "admin", 
 8             "cname": "admin", 
 9             "sex": "男", 
10             "password": "123456", 
11             "identity": "415555555555555551", 
12             "telephone": "15255555555", 
13             "address": "河南省新乡市", 
14             "birthday": "1999-06-15", 
15             "identification": "1" 
16         }, { 
17             "id": 2, 
18             "account": "张三", 
19             "cname": "张三", 
20             "sex": "男", 
21             "password": "123456", 
22             "identity": "415555555555555552", 
23             "telephone": "15255555555", 
24             "address": "河南省商丘市", 
25             "birthday": "1999-06-15", 
26             "identification": "1" 
27         }], 
28         "total": 100, 
29         "size": 20, 
30         "current": 1, 
31         "orders": [], 
32         "searchCount": true, 
33         "pages": 23 
34     } 
35 }

3.1、当然了,上面那个封装的也要接着使用,还需要再封装一个。那么可以再封装一个工具类,定义七个参数,分别是records、total、size、current、orders、searchCount、pages。

 1 package com.bie.demo.utils; 
 2  
 3  
 4 import com.bie.demo.po.CustomerInfo; 
 5  
 6 import java.util.Arrays; 
 7 import java.util.List; 
 8  
 9 /** 
10  * 
11  */ 
12 public class CustomerInfoResult { 
13  
14     private List<CustomerInfo> records; 
15     private long total; 
16     private int size; 
17     private int current; 
18     private int[] orders; 
19     private boolean searchCount; 
20     private long pages; 
21  
22     public List<CustomerInfo> getRecords() { 
23         return records; 
24     } 
25  
26     public void setRecords(List<CustomerInfo> records) { 
27         this.records = records; 
28     } 
29  
30     public long getTotal() { 
31         return total; 
32     } 
33  
34     public void setTotal(long total) { 
35         this.total = total; 
36     } 
37  
38     public int getSize() { 
39         return size; 
40     } 
41  
42     public void setSize(int size) { 
43         this.size = size; 
44     } 
45  
46     public int getCurrent() { 
47         return current; 
48     } 
49  
50     public void setCurrent(int current) { 
51         this.current = current; 
52     } 
53  
54     public int[] getOrders() { 
55         return orders; 
56     } 
57  
58     public void setOrders(int[] orders) { 
59         this.orders = orders; 
60     } 
61  
62     public boolean isSearchCount() { 
63         return searchCount; 
64     } 
65  
66     public void setSearchCount(boolean searchCount) { 
67         this.searchCount = searchCount; 
68     } 
69  
70     public long getPages() { 
71         return pages; 
72     } 
73  
74     public void setPages(long pages) { 
75         this.pages = pages; 
76     } 
77  
78     @Override 
79     public String toString() { 
80         return "CustomerInfoResult{" + 
81                 "records=" + records + 
82                 ", total=" + total + 
83                 ", size=" + size + 
84                 ", current=" + current + 
85                 ", orders=" + Arrays.toString(orders) + 
86                 ", searchCount=" + searchCount + 
87                 ", pages=" + pages + 
88                 '}'; 
89     } 
90 }

3.2、将查询返回的结果进行封装返回,最后再次进行封装,得到你想要的格式即可,如果失败了,或者成功了,如何进行调用。如下所示:

主要根据自己想要的格式进行封装哈。

 1 package com.bie.demo.controller; 
 2  
 3 import com.bie.demo.po.CustomerInfo; 
 4 import com.bie.demo.service.CustomerInfoService; 
 5 import com.bie.demo.utils.CustomerInfoResult; 
 6 import com.bie.demo.utils.NationalPolicyResult; 
 7 import org.springframework.beans.factory.annotation.Autowired; 
 8 import org.springframework.stereotype.Controller; 
 9 import org.springframework.web.bind.annotation.RequestMapping; 
10 import org.springframework.web.bind.annotation.RequestParam; 
11 import org.springframework.web.bind.annotation.ResponseBody; 
12  
13 import java.util.List; 
14  
15 /** 
16  * 
17  */ 
18 @Controller 
19 @RequestMapping(value = "/customerInfo") 
20 public class CustomerInfoController { 
21  
22     @Autowired 
23     private CustomerInfoService customerInfoService; 
24  
25  
26     @RequestMapping(value = "/selectCustomerInfoAll") 
27     @ResponseBody 
28     public NationalPolicyResult selectCustomerInfoAll() { 
29         // 查询返回所有的数据 
30         List<CustomerInfo> customerInfos = customerInfoService.selectCustomerInfoAll(); 
31         // 封装指定的json格式数据 
32         CustomerInfoResult customerInfoResult = new CustomerInfoResult(); 
33         customerInfoResult.setRecords(customerInfos); 
34         customerInfoResult.setTotal(100); 
35         customerInfoResult.setSize(20); 
36         customerInfoResult.setCurrent(1); 
37         customerInfoResult.setOrders(new int[0]); 
38         customerInfoResult.setSearchCount(true); 
39         customerInfoResult.setPages(23); 
40  
41         // 再次封装指定的json格式数据 
42         NationalPolicyResult nationalPolicyResult = new NationalPolicyResult(); 
43         NationalPolicyResult result = null; 
44         if (customerInfos != null && customerInfos.size() > 0 && !customerInfos.isEmpty()) { 
45             result = nationalPolicyResult.success(customerInfoResult); 
46         } else { 
47             result = nationalPolicyResult.build(1, "失败了......."); 
48         } 
49         return result; 
50     } 
51 }

3.3、页面调用一下,看看是否正确的返回结果。

使用json在线解析,查看是否是正确的json格式。 

那么快根据你的文档需求进行JSON封装吧。

作者:别先生

博客园:IT虾米网

如果您想及时得到个人撰写文章以及著作的消息推送,可以扫描上方二维码,关注个人公众号哦。


发布评论
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

Java中使用Jackson,对JSON和对象进行转换知识解答
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。