fastJson和 jackson的用法以及解析复杂Json

一:jackson

使用Jackson的依赖

 
com.fasterxml.jackson.core 
jackson-databind 
2.9.1 

Jackson的基本用法:

package com.ssl.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssl.domain.Person;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * author ssl
 * Jackson的基础用法
 */
public class jacksonTest {
    //Java转json对象
    @Test
    public void test1() throws JsonProcessingException {
        //1 创建对象
        Person person = new Person();
        person.setName("ssl");
        person.setAge(23);
        person.setSex("nan");
        //2创建Jackson的核心对象,ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        /**
         * 转换方法:
         *      writeValue(参数1,obj)
         *          参数1:
         *              File : 将Obj对象转换为Json字符串,并保存到指定的文件中
         *              Writer :将Obj对象转换为Json字符串,并将json数据填充到字符输出流中
         *              OutputStream :将Obj对象转换为Json字符串,并将json数据填充到字节输出流中
         *      writeValueAsString(Obj):将对象转换为json字符串
         */

        String s = objectMapper.writeValueAsString(person);
        System.out.println(s);
    }

    @Test
    public void test2() throws IOException {
        //1 创建对象
        Person person = new Person();
        person.setName("ssl");
        person.setAge(23);
        person.setSex("nan");
        person.setBirthday(new Date());
        //2创建Jackson的核心对象,ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        /**
         * 转换方法:
         *      writeValue(参数1,obj)
         *          参数1:
         *              File : 将Obj对象转换为Json字符串,并保存到指定的文件中
         *              Writer :将Obj对象转换为Json字符串,并将json数据填充到字符输出流中
         *              OutputStream :将Obj对象转换为Json字符串,并将json数据填充到字节输出流中
         *      writeValueAsString(Obj):将对象转换为json字符串
         */

        String s = objectMapper.writeValueAsString(person);
        objectMapper.writeValue(new File("src/main/java/com/ssl/person.txt"),person);
        System.out.println(s);//{"name":"ssl","age":23,"sex":"nan","birthday":1594635792141}

    }

    @Test
    public void test3() throws JsonProcessingException {
        //1 创建对象
        Person person = new Person();
        person.setName("ssl");
        person.setAge(23);
        person.setSex("nan");
        person.setBirthday(new Date());
        Person person1 = new Person();
        person1.setName("ssl");
        person1.setAge(23);
        person1.setSex("nan");
        person1.setBirthday(new Date());
        Person person2 = new Person();
        person2.setName("ssl");
        person2.setAge(23);
        person2.setSex("nan");
        person2.setBirthday(new Date());
        List list = new ArrayList();
        list.add(person);
        list.add(person1);
        list.add(person2);
        //2创建Jackson的核心对象,ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(list);
        System.out.println(s);
    }
    @Test
    public void test4() throws JsonProcessingException {
        Map map = new  HashMap();
        map.put("name","lisi");
        map.put("age",23);
        map.put("gender","nan");
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(map);
        System.out.println(s);
    }

    //Json转Java对象
    @Test
    public void test5() throws IOException {
//        String s ="{\"name\":\"ssl\",\"age\":23,\"sex\":\"nan\",\"birthday\":\"2020-10-11 13:23\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        //从Reader中读取对象
//        Reader reader = new StringReader(s);
        //从File中读取对象
//        File file = new File("src/main/java/com/ssl/person.json");
        //从Url中读取对象
//        URL url = new URL("file:src/main/java/com/ssl/person.json");
        //从InputStream中读取对象
        InputStream input = new FileInputStream("src/main/java/com/ssl/person.json");
        //接收两个参数,一个是json对象,另一个是要转换的对象的字节码
        Person p = objectMapper.readValue(input,Person.class);
        System.out.println(p.toString());
    }
    @Test
    public void test6(){
        String carJson =
                "{ \"brand\" : \"Mercedes\", \"doors\" : 5," +
                        "  \"owners\" : [\"John\", \"Jack\", \"Jill\"]," +
                        "  \"nestedObject\" : { \"field\" : \"value\" } }";

        ObjectMapper objectMapper = new ObjectMapper();


        try {

            JsonNode jsonNode = objectMapper.readValue(carJson, JsonNode.class);

            JsonNode brandNode = jsonNode.get("brand");
            String brand = brandNode.asText();
            System.out.println("brand = " + brand);

            JsonNode doorsNode = jsonNode.get("doors");
            int doors = doorsNode.asInt();
            System.out.println("doors = " + doors);

            JsonNode array = jsonNode.get("owners");
            JsonNode nestNode = array.get(0);
            String john = nestNode.asText();
            System.out.println("john  = " + john);

            JsonNode child = jsonNode.get("nestedObject");
            JsonNode childField = child.get("field");
            String field = childField.asText();
            System.out.println("field = " + field);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Jackson解析复杂json操作:

package com.ssl.fuzaJsonByJackson;

import java.io.Serializable;
import java.util.List;

public class LogisticsInfo implements Serializable {

    private static final long serialVersionUID = 6951873346591540974L;

    /**
     * 快递公司识别码
     */
    private String comCode;

    /**
     * 快递单号
     */
    private String postNo;

    /**
     * 快递物流信息查询是否成功
     */
    private boolean success;

    /**
     * 快递查询失败原因
     */
    private String failReason;

    /**
     * 快递物流状态
     */
    private int state;

    /**
     * 快递物流轨迹信息
     */
    List logisticsTraceList;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getComCode() {
        return comCode;
    }

    public void setComCode(String comCode) {
        this.comCode = comCode;
    }

    public String getPostNo() {
        return postNo;
    }

    public void setPostNo(String postNo) {
        this.postNo = postNo;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getFailReason() {
        return failReason;
    }

    public void setFailReason(String failReason) {
        this.failReason = failReason;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public List getLogisticsTraceList() {
        return logisticsTraceList;
    }

    public void setLogisticsTraceList(List logisticsTraceList) {
        this.logisticsTraceList = logisticsTraceList;
    }

    @Override
    public String toString() {
        return "LogisticsInfo{" +
                "comCode='" + comCode + '\'' +
                ", postNo='" + postNo + '\'' +
                ", success=" + success +
                ", failReason='" + failReason + '\'' +
                ", state=" + state +
                ", logisticsTraceList=" + logisticsTraceList +
                '}';
    }
}
package com.ssl.fuzaJsonByJackson;

import java.io.Serializable;

public class LogisticsTrace implements Serializable {

    private static final long serialVersionUID = -5152487306550447774L;

    /**
     * 接收时间
     */
    private String acceptTime;

    /**
     * 物流描述
     */
    private String acceptStation;

    /**
     * 备注信息
     */
    private String remark;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getAcceptTime() {
        return acceptTime;
    }

    public void setAcceptTime(String acceptTime) {
        this.acceptTime = acceptTime;
    }

    public String getAcceptStation() {
        return acceptStation;
    }

    public void setAcceptStation(String acceptStation) {
        this.acceptStation = acceptStation;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    @Override
    public String toString() {
        return "LogisticsTrace{" +
                "acceptTime='" + acceptTime + '\'' +
                ", acceptStation='" + acceptStation + '\'' +
                ", remark='" + remark + '\'' +
                '}';
    }
}
package com.ssl.fuzaJsonByJackson;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LogisticsUtils {
    /**
     * 解析通过「A」接口提供方获取的物流信息
     * json 解析: jackson, https://www.baeldung.com/jackson
     *
     * @param jsonStr 物流信息,json 格式字符串
     * @return 封装后的物流信息
     */
    public static LogisticsInfo getLogisticsInfoByA(String jsonStr) throws IOException {

        LogisticsInfo logisticsInfo = new LogisticsInfo();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonStr);
        String comCode = rootNode.get("comCodeA") != null ? rootNode.get("comCodeA").asText() : "";
        String postNo = rootNode.get("postNoA") != null ? rootNode.get("postNoA").asText() : "";
        boolean success = rootNode.get("successA") != null ? rootNode.get("successA").asBoolean() : false;
        String failReason = rootNode.get("failReasonA") != null ? rootNode.get("failReasonA").asText() : "";
        int state = rootNode.get("stateA") != null ? rootNode.get("stateA").asInt() : 0;

        logisticsInfo.setComCode(comCode);
        logisticsInfo.setPostNo(postNo);
        logisticsInfo.setSuccess(success);
        logisticsInfo.setFailReason(failReason);
        logisticsInfo.setState(state);
        /**
         * 遍历物流轨迹
         */
        if (rootNode.get("tracesA") != null && rootNode.get("tracesA").size() > 0) {
            List logisticsTraceList = new ArrayList<>(16);
            LogisticsTrace logisticsTrace;
            JsonNode traceNode = rootNode.get("tracesA");
            for (int i = 0; i < traceNode.size(); i++) {
                logisticsTrace = new LogisticsTrace();
                logisticsTrace.setAcceptTime(traceNode.get(i).get("acceptTimeA").asText());
                logisticsTrace.setAcceptStation(traceNode.get(i).get("acceptStationA").asText());
                logisticsTraceList.add(logisticsTrace);
            }
            logisticsInfo.setLogisticsTraceList(logisticsTraceList);
        }
        return logisticsInfo;
    }

    /**
     * 解析通过「B」接口提供方获取的物流信息
     * json 解析: jackson, https://www.baeldung.com/jackson
     *
     * @param jsonStr 物流信息,json 格式字符串
     * @return 封装后的物流信息
     */
    public static LogisticsInfo getLogisticsInfoByB(String jsonStr) throws IOException {
        LogisticsInfo logisticsInfo = new LogisticsInfo();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonStr);
        String comCode = rootNode.get("comCodeB") != null ? rootNode.get("comCodeB").asText() : "";
        String postNo = rootNode.get("postNoB") != null ? rootNode.get("comCodeB").asText() : "";
        boolean success = rootNode.get("successB") != null ? rootNode.get("successB").asBoolean() : false;
        String failReason = rootNode.get("failReasonB") != null ? rootNode.get("failReasonB").asText() : "";
        int state = rootNode.get("stateB") != null ? rootNode.get("stateB").asInt() : 0;

        logisticsInfo.setComCode(comCode);
        logisticsInfo.setPostNo(postNo);
        logisticsInfo.setSuccess(success);
        logisticsInfo.setFailReason(failReason);
        logisticsInfo.setState(state);
        /**
         * 遍历物流轨迹
         */
        if (rootNode.get("tracesB") != null && rootNode.get("tracesB").size() > 0) {
            List logisticsTraceList = new ArrayList<>(16);
            LogisticsTrace logisticsTrace;
            JsonNode traceNode = rootNode.get("tracesB");
            for (int i = 0; i < traceNode.size(); i++) {
                logisticsTrace = new LogisticsTrace();
                logisticsTrace.setAcceptTime(traceNode.get(i).get("acceptTimeB").asText());
                logisticsTrace.setAcceptStation(traceNode.get(i).get("acceptStationB").asText());
                logisticsTraceList.add(logisticsTrace);
            }
            logisticsInfo.setLogisticsTraceList(logisticsTraceList);
        }
        return logisticsInfo;
    }



    private LogisticsUtils(){}
}
package com.ssl.fuzaJsonByJackson;

import org.junit.jupiter.api.Test;

import java.io.IOException;

public class LogisticsUtilsTest {
    @Test
    public void getLogisticsInfoByA() throws IOException {

        String jsonStrA = "{" +
                "            \"comCodeA\": \"YTO\"," +
                "            \"postNoA\": \"M0101065279\"," +
                "            \"successA\": true," +
                "            \"failReasonA\": \"\"," +
                "            \"stateA\": 3," +
                "            \"tracesA\": [" +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-10 20:01:04\"," +
                "                    \"acceptStationA\": \"【上海市德玛西亚公司】 已收件\"" +
                "                }," +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-10 22:20:33\"," +
                "                    \"acceptStationA\": \"【上海市德玛西亚公司】 已打包\"" +
                "                }," +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-10 22:23:13\"," +
                "                    \"acceptStationA\": \"【上海市德玛西亚公司】 已发出 下一站 【上海转运中心】\"" +
                "                }," +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-11 03:07:34\"," +
                "                    \"acceptStationA\": \"【上海转运中心】 已收入\"" +
                "                }," +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-11 03:14:21\"," +
                "                    \"acceptStationA\": \"【上海转运中心】 已发出 下一站 【杭州转运中心】\"" +
                "                }," +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-11 10:37:02\"," +
                "                    \"acceptStationA\": \"【杭州转运中心】 已收入\"" +
                "                }," +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-11 13:11:00\"," +
                "                    \"acceptStationA\": \"【杭州转运中心】 已发出 下一站 【石桥转运中心】\"" +
                "                }," +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-11 22:45:20\"," +
                "                    \"acceptStationA\": \"【石桥转运中心】 已收入\"" +
                "                }," +
                "                {" +
                "                    \"acceptTimeA\": \"2018-09-12 13:19:39\"," +
                "                    \"acceptStationA\": \"客户 签收人: 圆通代签 已签收 感谢使用圆通速递,期待再次为您服务\"" +
                "                }" +
                "            ]" +
                "        }" +
                "}";
        LogisticsInfo logisticsInfo = LogisticsUtils.getLogisticsInfoByA(jsonStrA);
        System.out.println("logisticsInfo: " + logisticsInfo);
    }

}

二:fastJson

package com.ssl.JsonToPojo;

public class TopTripType {
    String key;
    String value;
    String poiId;
    boolean isJump;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getPoiId() {
        return poiId;
    }

    public void setPoiId(String poiId) {
        this.poiId = poiId;
    }

    public boolean isJump() {
        return isJump;
    }

    public void setJump(boolean jump) {
        isJump = jump;
    }
}

package com.ssl.JsonToPojo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws IOException {
        File file = new File("src/main/java/com/ssl/demo.json");
        String content = FileUtils.readFileToString(file);
        List topTripTypes = parseResponseData(content);
        for (int i = 0; i < topTripTypes.size(); i++) {
            System.out.println(topTripTypes.get(i).getKey());
        }

    }
    public static List parseResponseData(String responseStr){
        List result;
        try {
            JSONObject object = JSON.parseObject(responseStr);
            JSONObject data = (JSONObject) object.get("Data");
            JSONArray jsonArray = data.getJSONArray("ThemeList");
            result = JSON.parseArray(jsonArray.toJSONString(), TopTripType.class);
        } catch (Exception e) {
            result = new ArrayList<>();
        }
        return result;
    }
}

 

你可能感兴趣的:(Spring系列)