JSON字符串数组转java对象三种方式

JSON字符串转java对象如下代码,下面我给了三种方式:阿里巴巴的fastjson、谷歌的gson和jackson。
下面的参数是接口方给我提供现有的参数,可以换成你们需要的。

1、实体类package com.example.demo.pojo;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;

@Table(name = "jackson")
@Entity
@JsonIgnoreProperties(ignoreUnknown = true) // jackson使用的注解,没有会报com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field
public class JsonPojo {
    // `Col_Key` int(50)
    @Id
    @JsonProperty(value = "Col_Key")   // jackson使用@JsonProperty,fastjson、gson使用@SerializedName
    private String colKey;
    // `Region` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "Region", nullable = false)
    @JsonProperty(value = "Region")     // value要转对象的值务必要与json字符串中字段对应
    private String region;
    // `Region_Name` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "Region_Name", nullable = false)
    @JsonProperty(value = "Region_Name")
    private String regionName;
    // `ProductLine` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "product_line", nullable = false)
    @JsonProperty(value = "ProductLine")
    private String productLine;
    // `WorkCenter_Code` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "work_center_code", nullable = false)
    @JsonProperty(value = "WorkCenter_Code")
    private String workcenterCode;
    // `WorkCenter_Name` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "work_center_name", nullable = false)
    @JsonProperty(value = "WorkCenter_Name")
    private String workcenterName;
    // `Plan_ID` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "Plan_ID", nullable = false)
    @JsonProperty(value = "Plan_ID")
    private String planId;
    // `Operation_Name` varchar(64)
    @Basic // 与数据库映射关系
    @Column(name = "Operation_Name", nullable = false)
    @JsonProperty(value = "Operation_Name")
    private String operationName;
    // `StartTime` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "start_time", nullable = false)
    @JsonProperty(value = "StartTime")
    private String startTime;
    // `EndTime` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "end_time", nullable = false)
    @JsonProperty(value = "EndTime")
    private String endTime;
    // `Report_Person` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "Report_Person", nullable = false)
    @JsonProperty(value = "Report_Person")
    private String reportPerson;
    // `Report_Person_Name` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "Report_Person_Name", nullable = false)
    @JsonProperty(value = "Report_Person_Name")
    private String reportPersonName;
    // `Report_Person_End` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "Report_Person_End", nullable = false)
    @JsonProperty(value = "Report_Person_End")
    private String reportPersonEnd;
    // `Report_Person_End_Name` varchar(50)
    @Basic // 与数据库映射关系
    @Column(name = "Report_Person_End_Name", nullable = false)
    @JsonProperty(value = "Report_Person_End_Name")
    private String reportPersonEndName;
    // `Link`
    @Basic // 与数据库映射关系
    @Column(name = "Link", nullable = false)
    @JsonProperty(value = "Link")
    private String link;

    public String getColKey() {
        return colKey;
    }

    public void setColKey(String colKey) {
        this.colKey = colKey;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getRegionName() {
        return regionName;
    }

    public void setRegionName(String regionName) {
        this.regionName = regionName;
    }

    public String getProductLine() {
        return productLine;
    }

    public void setProductLine(String productLine) {
        this.productLine = productLine;
    }

    public String getWorkcenterCode() {
        return workcenterCode;
    }

    public void setWorkcenterCode(String workcenterCode) {
        this.workcenterCode = workcenterCode;
    }

    public String getWorkcenterName() {
        return workcenterName;
    }

    public void setWorkcenterName(String workcenterName) {
        this.workcenterName = workcenterName;
    }

    public String getPlanId() {
        return planId;
    }

    public void setPlanId(String planId) {
        this.planId = planId;
    }

    public String getOperationName() {
        return operationName;
    }

    public void setOperationName(String operationName) {
        this.operationName = operationName;
    }

    public String getStartTime() {
        return startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public String getReportPerson() {
        return reportPerson;
    }

    public void setReportPerson(String reportPerson) {
        this.reportPerson = reportPerson;
    }

    public String getReportPersonName() {
        return reportPersonName;
    }

    public void setReportPersonName(String reportPersonName) {
        this.reportPersonName = reportPersonName;
    }

    public String getReportPersonEnd() {
        return reportPersonEnd;
    }

    public void setReportPersonEnd(String reportPersonEnd) {
        this.reportPersonEnd = reportPersonEnd;
    }

    public String getReportPersonEndName() {
        return reportPersonEndName;
    }

    public void setReportPersonEndName(String reportPersonEndName) {
        this.reportPersonEndName = reportPersonEndName;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    @Override
    public String toString() {
        return "JsonPojo{" +
            "colKey='" + colKey + '\'' +
            ", region='" + region + '\'' +
            ", regionName='" + regionName + '\'' +
            ", productLine='" + productLine + '\'' +
            ", workcenterCode='" + workcenterCode + '\'' +
            ", workcenterName='" + workcenterName + '\'' +
            ", planId='" + planId + '\'' +
            ", operationName='" + operationName + '\'' +
            ", startTime='" + startTime + '\'' +
            ", endTime='" + endTime + '\'' +
            ", reportPerson='" + reportPerson + '\'' +
            ", reportPersonName='" + reportPersonName + '\'' +
            ", reportPersonEnd='" + reportPersonEnd + '\'' +
            ", reportPersonEndName='" + reportPersonEndName + '\'' +
            ", link='" + link + '\'' +
            '}';
    }
}

2、测试类

package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.pojo.JsonPojo;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;

public class JsonStringList {

    String jsonListStr = "[{\"Region\":\"AC2_1\",\"Region_Name\":\"WXAC总装车间ESC\",\"ProductLine\":\"ZX\",\"WorkCenter_Code\":\"CK01\",\"WorkCenter_Name\":\"仓库备料\",\"Plan_ID\":null,\"Operation_Name\":\"成品下线-PRO\",\"StartTime\":null,\"EndTime\":null,\"Report_Person\":null,\"Report_Person_Name\":null,\"Report_Person_End\":null,\"Report_Person_End_Name\":null,\"Link\":\"\",\"Col_Key\":\"CK01\"},{\"Region\":\"AC2_1\",\"Region_Name\":\"WXAC总装车间ESC\",\"ProductLine\":\"Z1\",\"WorkCenter_Code\":\"CS01\",\"WorkCenter_Name\":\"总_功能测试1\",\"Plan_ID\":null,\"Operation_Name\":null,\"StartTime\":null,\"EndTime\":null,\"Report_Person\":null,\"Report_Person_Name\":null,\"Report_Person_End\":null,\"Report_Person_End_Name\":null,\"Link\":\"\",\"Col_Key\":\"CS01\"}]";
    // 方式一:通过jackson,将json字符串数组转java对象(声明:这里不用在pom.xml中引入依赖是因为spring-boot-starter-web底层已经集成了jackson)
    public String jacksonMethod() {
        try {
            ObjectMapper mapper = new ObjectMapper();
            // 可以代替实体类@JsonIgnoreProperties(ignoreUnknown = true)
            //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            List lendReco = mapper.readValue(jsonListStr,new TypeReference>() { });
            for (int i = 0;i < lendReco.size();i++){
                JsonPojo jsonPojo = lendReco.get(i);
                System.out.println(jsonPojo.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }
    // 方式二:通过阿里巴巴的fastjson,将json字符串数组转java对象
    public String alibabaMethod(){
        List jacksonList = (List) JSON.parseArray(jsonListStr, JsonPojo.class);
        for (JsonPojo jsonPojo : jacksonList) {
            System.out.println(jsonPojo.toString());
        }
        return "success";
    }
    // 方式三:通过谷歌的Gson,将json字符串数组转java对象
    public String gsonMethod(){
        Gson gson = new Gson();
        List jsonPojoList = gson.fromJson(jsonListStr,new TypeToken>(){}.getType());
        for (JsonPojo jsonPojo : jsonPojoList) {
            System.out.println(jsonPojo.toString());
        }
        return "success";
    }

    public static void main(String[] args) {
        JsonStringList jsonStringList = new JsonStringList();
        // 方式一:jackson
        System.out.println(jsonStringList.jacksonMethod());
        // 方式二:fastjson
        //System.out.println(jsonStringList.alibabaMethod());
        // 方式三:gson
        //System.out.println(jsonStringList.gsonMethod());
    }
}

3、以上我是使用jackson进行的测试,另外两种方式我都注释了,大家可以自己尝试,但是要注意以下几点

①、导包:

springboot项目中spring-boot-starter-web自动集成了jackson所需要的所有jar包,在pom.xml中无需自行添加依赖。只需

添加fastjson依赖:


    com.alibaba
    fastjson
    1.2.51

添加gson依赖:


    com.google.code.gson
    gson
    2.6.2

②、fastjson和gson方式相同

将实体类中的@JsonProperty变成@SerializedName以及去掉类上的@JsonIgnoreProperties(ignoreUnknown = true)或者测试类中所使用到的 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false),这两种方式只针对jackson使用,并且只使用其中一个就能解决报错:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field的问题。

③、以上已经全部测试过,亲测可用。

④、需要pom.xml的朋友可以到我的百度云下载

链接:https://pan.baidu.com/s/1W4rj1UH6nBTAgc9jMMZviQ 
提取码:rr2n 

你可能感兴趣的:(fastjson,jackson,gson)