这段工作中总会遇到使用Java处理JSON的情况,大部分都使用的是开源工具Jackson实现的。因此总结一下发上来,希望对看到的人有所帮助。
上一篇文档中,我已经讲过Java如何使用Jackson来对Json进行序列化,这边我再稍微回顾一下。
Jackson中有个ObjectMapper类很是实用,用于Java对象与JSON的互换。
1、Java对象转换为JSON:
User user=new User(); //Java Object
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(user); //返回字符串
//输出格式化后的字符串(有性能损耗)
mapper.defaultPrettyPrintingWriter().writeValueAsString(user);
mapper.writeValue(new File("c:\\user.json"), user); //指定文件写入
//设置序列化配置(全局),设置序列化时不输出空值.
sharedMapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
2、JSON反序列化为Java对象:
ObjectMapper mapper = new ObjectMapper();
//解析器支持解析单引号
mapper.configure(Feature.ALLOW_SINGLE_QUOTES,true);
//解析器支持解析结束符
mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS,true);
HashMap jsonMap = mapper.readValue(json,HashMap.class); //转换为HashMap对象
下面讲解一下Jackson对Json的基本操作:
Map转换为json
package com.pcmall; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class Map2Json { /** * Map 转换为 json */ public static void MyTest01() { Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("name", "zhang"); hashMap.put("sex", "1"); hashMap.put("login", "Jack"); hashMap.put("password", "123abc"); try { ObjectMapper objectMapper = new ObjectMapper(); String userMapJson = objectMapper.writeValueAsString(hashMap); JsonNode node = objectMapper.readTree(userMapJson); // 输出结果转意,输出正确的信息 System.out.println(node.get("password").asText()); // 输出不转意,输出结果会包含"",这是不正确的,除非作为json传递,如果是输出结果值,必须如上一行的操作 System.out.println(node.get("name")); } catch (IOException e) { } } public static void main(String[] args){ MyTest01(); } }
输出结果如下:
123abc "zhang"
解析json格式字符串
package com.pcmall; import java.io.IOException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class ResolveJson { /** * 解析 json 格式字符串 */ public static void MyTest02() { try { String str = "{\"data\":{\"birth_day\":7,\"birth_month\":6},\"errcode\":0,\"msg\":\"ok\",\"ret\":0}"; ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(str); JsonNode data = root.path("data"); JsonNode birth_day = data.path("birth_day"); System.out.println(birth_day.asInt()); JsonNode birth_month = data.path("birth_month"); System.out.println(birth_month.asInt()); JsonNode msg = root.path("msg"); System.out.println(msg.textValue()); } catch (IOException e) { } } public static void main(String[] args){ MyTest02(); } }输出结果如下:
7 6 ok
json直接提取值
package com.pcmall; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class GetPartJson { /** * json 直接提取 值 */ public static void MyTest03() { try { // 演示字符串 String str = "{\"data\":{\"hasnext\":0,\"info\":[{\"id\":\"288206077664983\",\"timestamp\":1371052476},{\"id\":\"186983078111768\",\"timestamp\":1370944068},{\"id\":\"297031120529307\",\"timestamp\":1370751789},{\"id\":\"273831022294863\",\"timestamp\":1369994812}],\"timestamp\":1374562897,\"totalnum\":422},\"errcode\":0,\"msg\":\"ok\",\"ret\":0,\"seqid\":5903702688915195270}"; ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(str); // 提取 data JsonNode data = root.path("data"); // 提取 info JsonNode info = data.path("info"); System.out.println(info.size()); // 得到 info 的第 0 个 JsonNode item = info.get(0); System.out.println(item.get("id")); System.out.println(item.get("timestamp")); // 得到 info 的第 2 个 item = info.get(2); System.out.println(item.get("id")); System.out.println(item.get("timestamp")); // 遍历 info 内的 array if (info.isArray()) { for (JsonNode objNode : info) { System.out.println(objNode); } } } catch (Exception e) { } } public static void main(String[] args){ MyTest03(); } }输出结果如下:
4 "288206077664983" 1371052476 "297031120529307" 1370751789 {"id":"288206077664983","timestamp":1371052476} {"id":"186983078111768","timestamp":1370944068} {"id":"297031120529307","timestamp":1370751789} {"id":"273831022294863","timestamp":1369994812}
创建一个Json,并向该json添加内容
package com.pcmall; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class CreateJson { /** * 创建一个 json,并向该 json 添加内容 */ public static void MyTest04() { try { ObjectMapper mapper = new ObjectMapper(); ObjectNode root1 = mapper.createObjectNode(); root1.put("nodekey1", 1); root1.put("nodekey2", 2); System.out.println(root1.toString()); //Create the root node ObjectNode root = mapper.createObjectNode (); //Create a child node ObjectNode node1 = mapper.createObjectNode (); node1.put ("nodekey1", 1); node1.put ("nodekey2", 2); //Bind the child nodes root.put ("child", node1); //Array of nodes ArrayNode arrayNode = mapper.createArrayNode (); arrayNode.add (node1); arrayNode.add (1); //Bind array node root.put ("arraynode", arrayNode); System.out.println (mapper.writeValueAsString (root)); // 得到的输出信息 // {"child":{"nodekey1":1,"nodekey2":2},"arraynode":[{"nodekey1":1,"nodekey2":2},1]} } catch (Exception e) { } } public static void main(String[] args){ MyTest04(); } }输出结果如下:
{"nodekey1":1,"nodekey2":2} {"child":{"nodekey1":1,"nodekey2":2},"arraynode":[{"nodekey1":1,"nodekey2":2},1]}
创建一个array node
package com.pcmall; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class CreateNodeArray { // 创建一个 array node public static void MyTest05() { try { ObjectMapper mapper = new ObjectMapper(); ArrayNode arrayNode = mapper.createArrayNode(); int i = 0; // 在 array 内创建 3 组 node 存入 array for (i = 0; i < 3; i++) { // 创建一个 node ObjectNode node = mapper.createObjectNode(); node.put("nodeA", i); node.put("nodeB", i); node.put("nodeC", i); // 向 array 内添 node arrayNode.add(node); } // 根 ObjectNode root = mapper.createObjectNode(); root.put("total", i); root.put("rows", arrayNode); System.out.println(mapper.writeValueAsString(root)); // 得到的输出信息 // {"total":3,"rows":[{"nodeA":0,"nodeB":0,"nodeC":0},{"nodeA":1,"nodeB":1,"nodeC":1},{"nodeA":2,"nodeB":2,"nodeC":2}]} } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args){ MyTest05(); } }输出结果如下:
{"total":3,"rows":[{"nodeA":0,"nodeB":0,"nodeC":0},{"nodeA":1,"nodeB":1,"nodeC":1},{"nodeA":2,"nodeB":2,"nodeC":2}]}
在添加 array 节点时,put node 的方法已经过时,将使用 set 方法 添加 array 节点,举例:
实际工作中应用
使用Firefox的RESTClient插件进行测试,输入URL,输出如下图所示的结果。
其中基础类如下:
import java.util.Date; public class SaleOrderItem { private String spxx01; private String spxx04; private float lsdi05; private Date lsdi11; private long lsd01; private long lsdi01; private float lsdi02; private String gsxx01; public String getSpxx01() { return spxx01; } public void setSpxx01(String spxx01) { this.spxx01 = spxx01; } public String getSpxx04() { return spxx04; } public void setSpxx04(String spxx04) { this.spxx04 = spxx04; } public float getLsdi05() { return lsdi05; } public void setLsdi05(float lsdi05) { this.lsdi05 = lsdi05; } public Date getLsdi11() { return lsdi11; } public void setLsdi11(Date lsdi11) { this.lsdi11 = lsdi11; } public long getLsd01() { return lsd01; } public void setLsd01(long lsd01) { this.lsd01 = lsd01; } public long getLsdi01() { return lsdi01; } public void setLsdi01(long lsdi01) { this.lsdi01 = lsdi01; } public float getLsdi02() { return lsdi02; } public void setLsdi02(float lsdi02) { this.lsdi02 = lsdi02; } public String getGsxx01() { return gsxx01; } public void setGsxx01(String gsxx01) { this.gsxx01 = gsxx01; } @Override public String toString(){ return spxx04; } }业务类使用Spring RestTemplate解析RESTful服务获取到Json,然后调用ObjectMapper对象mapper的readValue(String,TypeReference)方法获取到SaleOrderItem列表。
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class RestWebservice { /** * @param args * @throws IOException * @throws JsonProcessingException * @throws Exception * @throws RestClientException */ public static void main(String[] args) throws JsonProcessingException, IOException{ RestTemplate restTemplate = new RestTemplate(); //get方式*********************************************************************************************************** //参数直接放在URL中 String message = restTemplate.getForObject("http://xxx.xxx.xxx.xxx:8080/pad/interface/poslsd/saleOrderDetail?saleOrder=5078603&gsxx=0001", String.class ); System.out.println(message); List<SaleOrderItem> saleOrderItems = new ArrayList<SaleOrderItem>(); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(message); JsonNode data = root.path("data"); String strData = data.toString(); if(data.isArray()){ saleOrderItems = mapper.readValue(strData, new TypeReference<List<SaleOrderItem>>(){}); System.out.println(saleOrderItems.size()); for(SaleOrderItem item : saleOrderItems){ System.out.println(item); } } } }输出结果如下:
{"code":10001,"message":"操作成功","total":1,"data":[{"spxx01":97321,"spxx04":"同方商用主机超越Z400","lsdi05":1.0,"lsdi11":1460044800000,"lsd01":5078603,"lsdi01":507860301,"lsdi02":2999.0,"gsxx01":"0001"}]} 1 同方商用主机超越Z400