目录
本文概览:通过jackSon将json转换成Object和将Object转成json。
1 引入
json在进行web数据传输时,所以会涉及到对象类型和json之间的互转。目前常用的有fastjson和jackson两类:
- jackson比较国际化,比较标准。如果没有对性能有特别强烈的要求,其实jackson应该更优先选择。
- fastjson是阿里开源的,望文生义,fastjson中“fast”说明了其引入的意义就是快。
2 maven库
需要引入三个库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!--jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.8</version> </dependency> <!--fastjson--> |
3 Json转Object
3.1 json转成Bean
1、定义一个Object对象
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 |
public class RecvInfo { private String bankUserId; private Long amount; private String bankName; public String getBankUserId() { return bankUserId; } public void setBankUserId(String bankUserId) { this.bankUserId = bankUserId; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE); } } |
2、解析代码如下
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 |
public class JsonUtil { /** * 转成一个Object对象 * * @param json * @param type * @param <T> * @return */ public static <T> T transfer2Obj(String json, Class<T> type) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.readValue(json, type); } catch (Exception e) { throw new RuntimeException("解析失败"); } } public static void main(String args[]) { String input = "{\"bankUserId\":\"4005\",\"amount\":2800,\"bankName\":\"邮储银行\",\"frontBankCode\":\"4005\"}"; RecvInfo info = JsonUtil.transfer2Obj(input, RecvInfo.class); System.out.println(info); } } |
3.2 json转成集合Collections
3.2.1 元素类型为基本类型
1、代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class JsonUtil { /** * 转成一个Object对象 * * @param json * @param type * @param <T> * @return */ public static <T> T transfer2Obj(String json, Class<T> type) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.readValue(json, type); } catch (Exception e) { throw new RuntimeException("解析失败"); } } } |
2、转成map测试如下
解析如下json
1 |
{"bankUserId":"4005","amount":2800,"bankName":"邮储银行","frontBankCode":"4005"} |
对应的测试代码为
1 2 3 4 5 |
public static void main(String args[]) { String input = "{\"bankUserId\":\"4005\",\"amount\":2800,\"bankName\":\"邮储银行\",\"frontBankCode\":\"4005\"}"; Map info = JsonUtil.transfer2Obj(input,Map.class); System.out.println(info); } |
执行结果为:
{bankUserId=4005, amount=2800, bankName=邮储银行, frontBankCode=4005}
3、解析list
解析如下json
[“bankUserId”,”4005″,”amount”,2800]
对应的代码如下:
1 2 3 4 5 |
public static void main(String args[]) { String input = "[\"bankUserId\",\"4005\",\"amount\",2800]"; List<Object> info = JsonUtil.transfer2Obj(input,List.class); System.out.println(info); } |
此时对于字符串转成String类型,数值转成了Interger对象。
3.2.2 复杂集合类-元素类型为Bean类型
当json中元素类型是一个Bean,不再是基本类型,如下代码
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 |
public class JsonUtil { /** * 将json转成复杂的集合类:List<Bean>或者Map<Bean,Bean> * * @param json * @param parametrized * @param parameterClasses * @param <T> * @return */ public static <T> T transfer2Collections(String json, Class<?> parametrized, Class<?>... parameterClasses) { try { ObjectMapper mapper = new ObjectMapper(); JavaType javaType = mapper.getTypeFactory().constructParametricType(parametrized, parameterClasses); return mapper.readValue(json, javaType); } catch (Exception e) { System.out.println(e.toString()); } return null; } public static void main(String args[]) { String input = "[{\"bankUserId\":\"4005\",\"amount\":2800,\"bankName\":\"邮储银行\"},{\"bankUserId\":\"4006\",\"amount\":800,\"bankName\":\"建设银行\"}]"; List<RecvInfo> recvInfoList = JsonUtil.transfer2Collections(input,ArrayList.class,RecvInfo.class); System.out.println(recvInfoList); } } |
4 Object转Json
4.1 将Object转成String类型的json
可以通过ObjectMapper#wirteValueAsString方法来实现,代码如下。不仅可以转Bean、还可以转List和Map类型的对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class JsonUtil { public static <T> String transfer2JsonString(T object){ String result = StringUtils.EMPTY; try { ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(object); System.out.printf(jsonString); } catch (Exception e) { System.out.printf("error"); } return result; } public static void main(String args[]) { Map map = Maps.newHashMap(); map.put("amount","1000"); map.put("bankCode","323"); String json = JsonUtil.transfer2JsonString(map); System.out.println(json); } } |
4.2 将Object转成Json保存到文件中
通过ObjectMapper#writeValue来实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class JsonUtil { /** * 转成json保存到文件中 * @param object * @param path * @param <T> */ public static <T> void transfer2JsonFile(T object,String path){ try { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(path),object); } catch (Exception e) { System.out.printf("error"); } } public static void main(String args[]) { Map map = Maps.newHashMap(); map.put("amount","1000"); map.put("bankCode","323"); JsonUtil.transfer2JsonFile(map,"/Users/HearThinkDo/jsonfile.txt"); } } |
执行结果为
HeartThinkDo@B000000064800:~$ cat jsonfile.txt
{“amount”:”1000″,”bankCode”:”323″}
(全文完)