1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 使用Java对返回的结果 封装成指定JSON格式的数据类型

使用Java对返回的结果 封装成指定JSON格式的数据类型

时间:2020-10-03 05:28:34

相关推荐

使用Java对返回的结果 封装成指定JSON格式的数据类型

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: /2/28 10:40 16 * @Version: 1.0 17 */ 18 public class NationalPolicyResult implements Serializable { 19 20/** 21* 22*/ 23private static final long serialVersionUID = 1L; 24 25// 定义jackson对象 26private static final ObjectMapper MAPPER = new ObjectMapper(); 27 28// 返回标记,成功标记为0,失败为1 29private Integer code; 30 31// 返回消息 32private String msg; 33 34// 返回中的数据 35private Object data; 36 37/** 38* 1、成功返回调用的方法 39* 40* @param data 41* @return 42*/ 43public static NationalPolicyResult success(Object data) { 44 return new NationalPolicyResult(data); 45} 46 47/** 48* 2、成功返回调用的方法,重载方法 49* 50* @return 51*/ 52public static NationalPolicyResult success() { 53 return new NationalPolicyResult(null); 54} 55 56 57/** 58* 3、传入封装的数据,返回标记和返回信息进行默认 59* 60* @param data 61*/ 62public NationalPolicyResult(Object data) { 63 this.code = 0; 64 this.msg = "success"; 65 this.data = data; 66} 67 68/** 69* 4、无参的构造方法 70*/ 71public NationalPolicyResult() { 72 73} 74 75/** 76* 5、自己构建一个方法,调用构造方法,返回自己封装的状态,返回信息,和封装的数据信息 77* 78* @param code 79* @param msg 80* @param data 81* @return 82*/ 83public 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*/ 94public static NationalPolicyResult build(Integer code, String msg) { 95 return new NationalPolicyResult(code, msg, null); 96} 97 98/** 99* 7、可以传入封装的数据,和封装的信息,失败或者成功100*101* @param data102* @param msg103*/104public 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 code115* @param msg116* @param data117*/118public NationalPolicyResult(Integer code, String msg, Object data) {119 this.code = code;120 this.msg = msg;121 this.data = data;122}123 124public Integer getCode() {125 return code;126}127 128public void setCode(Integer code) {129 this.code = code;130}131 132public String getMsg() {133 return msg;134}135 136public void setMsg(String msg) {137 this.msg = msg;138}139 140public Object getData() {141 return data;142}143 144public 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* @return155*/156public 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 json181* @return182*/183public 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* @return198*/199public 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(),206MAPPER.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 @Controller16 @RequestMapping(value = "/customerInfo")17 public class CustomerInfoController {18 19@Autowired20private CustomerInfoService customerInfoService;21 22@RequestMapping(value = "/selectCustomerInfoById")23@ResponseBody24public 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": 2334}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 14private List<CustomerInfo> records;15private long total;16private int size;17private int current;18private int[] orders;19private boolean searchCount;20private long pages;21 22public List<CustomerInfo> getRecords() {23 return records;24}25 26public void setRecords(List<CustomerInfo> records) {27 this.records = records;28}29 30public long getTotal() {31 return total;32}33 34public void setTotal(long total) {35 this.total = total;36}37 38public int getSize() {39 return size;40}41 42public void setSize(int size) {43 this.size = size;44}45 46public int getCurrent() {47 return current;48}49 50public void setCurrent(int current) {51 this.current = current;52}53 54public int[] getOrders() {55 return orders;56}57 58public void setOrders(int[] orders) {59 this.orders = orders;60}61 62public boolean isSearchCount() {63 return searchCount;64}65 66public void setSearchCount(boolean searchCount) {67 this.searchCount = searchCount;68}69 70public long getPages() {71 return pages;72}73 74public void setPages(long pages) {75 this.pages = pages;76}77 78@Override79public 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 @Controller19 @RequestMapping(value = "/customerInfo")20 public class CustomerInfoController {21 22@Autowired23private CustomerInfoService customerInfoService;24 25 26@RequestMapping(value = "/selectCustomerInfoAll")27@ResponseBody28public 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封装吧。

作者:别先生

博客园:/biehongli/

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。