java中json和对象之间相互转换的运用

寻技术 JS脚本 / JAVA编程 2023年08月25日 148

1.目录结构

2.配置相关文件

2.1.引入相关的pom文件

pom.xml

<dependencies>
        <!-- JSON -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.8</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.24</version>
        </dependency>
    </dependencies>

2.2.配置引入json文件工具类

PurUtil.java

package util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PurUtil {
    /**
     * 读取json文件方法
     * @param url
     * @return
     */
    public static  String readWithFileInputStream(String url){
        // 创建一个 File 对象,表示要读取的文件
        File file = new File(url);
        // 创建一个 StringBuilder 对象,用来存储读取到的字符串
        StringBuilder sb = new StringBuilder();
        try {
            // 创建一个 FileReader 对象,用来读取文件的字符流
            FileReader fr = new FileReader(file);
            // 创建一个 BufferedReader 对象,用来缓冲字符流,并提供按行读取的方法
            BufferedReader br = new BufferedReader(fr);
            // 定义一个变量,用来存储每行的内容
            String line;
            // 循环读取每一行,直到文件结束
            while ((line = br.readLine()) != null) {
                // 将每行的内容追加到 StringBuilder 中,并添加换行符
                sb.append(line).append("\n");
            }
            // 关闭 BufferedReader 和 FileReader
            br.close();
            fr.close();
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
        // 将 StringBuilder 转换为字符串,并打印输出
        String json = sb.toString();
        return json;
    }
}

2. 3.配置JSON和对象相互转化工具类

JsonUtil.java

package util;
import com.alibaba.fastjson.JSON;
public class JsonUtil {
    public static String getJson(Object object){
       return JSON.toJSONString(object);
    }
    public static <T> T fromJson(String json, Class<T> clazz) {
        return JSON.parseObject(json,clazz);
    }
}

2.4.配置java对象

Columns.java

package entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Columns {
    @JsonProperty("Name")
    private String name;
    @JsonProperty("Caption")
    private String caption;
    @JsonProperty("DataType")
    private String dataType;
    public Columns() {
    }
    public Columns(String name, String caption, String dataType) {
        this.name = name;
        this.caption = caption;
        this.dataType = dataType;
    }
    @JSONField(name = "Name")
    public String getName() {
        return name;
    }
    @JSONField(name = "Name")
    public void setName(String name) {
        this.name = name;
    }
    @JSONField(name = "Caption")
    public String getCaption() {
        return caption;
    }
    @JSONField(name = "Caption")
    public void setCaption(String caption) {
        this.caption = caption;
    }
    @JSONField(name = "DataType")
    public String getDataType() {
        return dataType;
    }
    @JSONField(name = "DataType")
    public void setDataType(String dataType) {
        this.dataType = dataType;
    }
}

IXbusPlanInfoBuild.java

package entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
public class IXbusPlanInfoBuild{
    @JsonProperty("MessageHeader")
    private MessageHeader messageHeader;
    @JsonProperty("Tables")
    private List<Table> listTab;
    public IXbusPlanInfoBuild(){
      this.messageHeader=new MessageHeader();
      this.listTab=new ArrayList<Table>();
      Table table=new Table();
        this.listTab.add(table);
    }
    @JSONField(name = "MessageHeader")
    public MessageHeader getMessageHeader() {
        return messageHeader;
    }
    public void setMessageHeader(MessageHeader messageHeader) {
        this.messageHeader = messageHeader;
    }
    @JSONField(name = "Tables")
    public List<Table> getListTab() {
        return listTab;
    }
    @JSONField(name = "Tables")
    public void setListTab(List<Table> listTab) {
        this.listTab = listTab;
    }
}

MessageHeader.java

package entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
public class MessageHeader {
    @JsonProperty("UUID")
    private String uuid;
    @JsonProperty("SvcName")
    private String svcName;
    @JsonProperty("Sender")
    private String sender;
    @JsonProperty("Receiver")
    private String receiver;
    @JsonProperty("MessageId")
    private String messageId;
    @JsonProperty("Msg")
    private String msg;
    @JsonProperty("Flag")
    private Integer flag;
    @JsonProperty("MessageTypeId")
    private String messageTypeId;
    @JsonProperty("SendDate")
    private String sendDate;
    @JsonProperty("SendTime")
    private String sendTime;
    @JSONField(name = "UUID")
    public String getUuid() {
        return uuid;
    }
    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
    @JSONField(name = "SvcName")
    public String getSvcName() {
        return svcName;
    }
    public void setSvcName(String svcName) {
        this.svcName = svcName;
    }
    @JSONField(name = "Sender")
    public String getSender() {
        return sender;
    }
    public void setSender(String sender) {
        this.sender = sender;
    }
    @JSONField(name = "Receiver")
    public String getReceiver() {
        return receiver;
    }
    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }
    @JSONField(name = "MessageId")
    public String getMessageId() {
        return messageId;
    }
    public void setMessageId(String messageId) {
        this.messageId = messageId;
    }
    @JSONField(name = "Msg")
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    @JSONField(name = "Flag")
    public Integer getFlag() {
        return flag;
    }
    public void setFlag(Integer flag) {
        this.flag = flag;
    }
    @JSONField(name = "MessageTypeId")
    public String getMessageTypeId() {
        return messageTypeId;
    }
    public void setMessageTypeId(String messageTypeId) {
        this.messageTypeId = messageTypeId;
    }
    @JSONField(name = "SendDate")
    public String getSendDate() {
        return sendDate;
    }
    public void setSendDate(String sendDate) {
        this.sendDate = sendDate;
    }
    @JSONField(name = "SendTime")
    public String getSendTime() {
        return sendTime;
    }
    public void setSendTime(String sendTime) {
        this.sendTime = sendTime;
    }
}

Rows.java

package entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Rows {
    @JsonProperty("MESSAGE")
    private String message;
    @JsonProperty("ACCOUNT_PERIOD")
    private String accountPeriod;
    @JsonProperty("MSG_TYPE")
    private String msgType;
    @JsonProperty("MR_LINE_ID")
    private String mrLineId;
    @JsonProperty("RETURN_TIME")
    private String returnTime;
    @JsonProperty("SYSTEM_ID")
    private String systemId;
    @JSONField(name = "MESSAGE")
    public String getMessage() {
        return message;
    }
    @JSONField(name = "MESSAGE")
    public void setMessage(String message) {
        this.message = message;
    }
    @JSONField(name = "ACCOUNT_PERIOD")
    public String getAccountPeriod() {
        return accountPeriod;
    }
    @JSONField(name = "ACCOUNT_PERIOD")
    public void setAccountPeriod(String accountPeriod) {
        this.accountPeriod = accountPeriod;
    }
    @JSONField(name = "MSG_TYPE")
    public String getMsgType() {
        return msgType;
    }
    @JSONField(name = "MSG_TYPE")
    public void setMsgType(String msgType) {
        this.msgType = msgType;
    }
    @JSONField(name = "MR_LINE_ID")
    public String getMrLineId() {
        return mrLineId;
    }
    @JSONField(name = "MR_LINE_ID")
    public void setMrLineId(String mrLineId) {
        this.mrLineId = mrLineId;
    }
    @JSONField(name = "RETURN_TIME")
    public String getReturnTime() {
        return returnTime;
    }
    @JSONField(name = "RETURN_TIME")
    public void setReturnTime(String returnTime) {
        this.returnTime = returnTime;
    }
    @JSONField(name = "SYSTEM_ID")
    public String getSystemId() {
        return systemId;
    }
    @JSONField(name = "SYSTEM_ID")
    public void setSystemId(String systemId) {
        this.systemId = systemId;
    }
}

Table.java

package entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
public class Table {
    @JsonProperty("Name")
    private String name;
    @JsonProperty("Columns")
    private List<Columns> listCol;
    @JsonProperty("Rows")
    private List<Rows> listRows;
    public Table(){
        this.listCol=new ArrayList<Columns>();
        this.listRows=new ArrayList<Rows>();
    }
    @JSONField(name = "Name")
    public String getName() {
        return name;
    }
    @JSONField(name = "Name")
    public void setName(String name) {
        this.name = name;
    }
    @JSONField(name = "Columns")
    public List<Columns> getListCol() {
        return listCol;
    }
    @JSONField(name = "Columns")
    public void setListCol(List<Columns> listCol) {
        this.listCol = listCol;
    }
    @JSONField(name = "Rows")
    public List<Rows> getListRows() {
        return listRows;
    }
    @JSONField(name = "Rows")
    public void setListRows(List<Rows> listRows) {
        this.listRows = listRows;
    }
}

说明: @JSONField在get方法进行设置,那么对象在转化为json格式的时候,将会按照JSONField设置的值进行转化;@JSONField在set方法设置,那么json格式字符串才会匹配注解上面一样的对象属性,然后对对象属性进行赋值。

2.5.配置测试工具类

2.5.1对象转化为json字符串

TestPut.java

package test;
import entity.*;
import util.JsonUtil;
import util.PurUtil;
import java.util.ArrayList;
import java.util.List;
public class TestPut {
    public static void main(String[] args) {
        String str2=JsonUtil.getJson(TestPut.getIXbusPlanInfoBuild());
        int a=1;
    }
    public static IXbusPlanInfoBuild getIXbusPlanInfoBuild(){
        IXbusPlanInfoBuild iXbusPlanInfoBuild=new IXbusPlanInfoBuild();
        MessageHeader messageHeader=new MessageHeader();
        messageHeader.setUuid("8ac4c0b689297e31018943de73433307");
        messageHeader.setSvcName("1012114110");
        messageHeader.setSender("1012");
        messageHeader.setReceiver("1141");
        messageHeader.setMessageId("");
        messageHeader.setMsg("");
        messageHeader.setFlag(0);
        messageHeader.setMessageTypeId("1012114110");
        messageHeader.setSendDate("20230711");
        messageHeader.setSendTime("153319");
        //table
        List<Table> listTab=new ArrayList<Table>();
        Table table=new Table();
        table.setName("BODY");
        List<Columns> listCol=new ArrayList<Columns>();
        Columns columns1=new Columns();
        columns1.setName("MR_LINE_ID");
        columns1.setCaption("计划行号");
        columns1.setDataType("S");
        listCol.add(columns1);
        Columns columns2=new Columns();
        columns2.setName("ACCOUNT_PERIOD");
        columns2.setCaption("会计期");
        columns2.setDataType("S");
        listCol.add(columns2);
        Columns columns3=new Columns();
        columns3.setName("RETURN_TIME");
        columns3.setCaption("反馈时间");
        columns3.setDataType("S");
        listCol.add(columns3);
        Columns columns4=new Columns();
        columns4.setName("MSG_TYPE");
        columns4.setCaption("消息类型(S:成功 ;E:失败)");
        columns4.setDataType("S");
        listCol.add(columns4);
        Columns columns5=new Columns();
        columns5.setName("MESSAGE");
        columns5.setCaption("消息内容");
        columns5.setDataType("S");
        listCol.add(columns5);
        Columns columns6=new Columns();
        columns6.setName("SYSTEM_ID");
        columns6.setCaption("系统别");
        columns6.setDataType("S");
        listCol.add(columns6);
        table.setListCol(listCol);
        List<Rows> listRow=new ArrayList<Rows>();
        Rows rows=new Rows();
        rows.setMessage("消息接收成功");
        rows.setAccountPeriod("202307");
        rows.setMsgType("S");
        rows.setMrLineId("BJJHGG01230700032-001");
        rows.setReturnTime("20230711153319");
        rows.setSystemId("1012");
        listRow.add(rows);
        table.setListRows(listRow);
        listTab.add(table);
        iXbusPlanInfoBuild.setMessageHeader(messageHeader);
        iXbusPlanInfoBuild.setListTab(listTab);
        return iXbusPlanInfoBuild;
    }
}

2.5.2字符串转化为对象

TestPut.java

package test;
import entity.*;
import util.JsonUtil;
import util.PurUtil;
import java.util.ArrayList;
import java.util.List;
public class TestPut {
    public static void main(String[] args) {
         String str= PurUtil.readWithFileInputStream("E:/java project/studyEntity1/src/main/resources/plan.json");
         IXbusPlanInfoBuild iXbusPlanInfoBuild=JsonUtil.fromJson(str,IXbusPlanInfoBuild.class);
        int a=1;
    }
    public static IXbusPlanInfoBuild getIXbusPlanInfoBuild(){
        IXbusPlanInfoBuild iXbusPlanInfoBuild=new IXbusPlanInfoBuild();
        MessageHeader messageHeader=new MessageHeader();
        messageHeader.setUuid("8ac4c0b689297e31018943de73433307");
        messageHeader.setSvcName("1012114110");
        messageHeader.setSender("1012");
        messageHeader.setReceiver("1141");
        messageHeader.setMessageId("");
        messageHeader.setMsg("");
        messageHeader.setFlag(0);
        messageHeader.setMessageTypeId("1012114110");
        messageHeader.setSendDate("20230711");
        messageHeader.setSendTime("153319");
        //table
        List<Table> listTab=new ArrayList<Table>();
        Table table=new Table();
        table.setName("BODY");
        List<Columns> listCol=new ArrayList<Columns>();
        Columns columns1=new Columns();
        columns1.setName("MR_LINE_ID");
        columns1.setCaption("计划行号");
        columns1.setDataType("S");
        listCol.add(columns1);
        Columns columns2=new Columns();
        columns2.setName("ACCOUNT_PERIOD");
        columns2.setCaption("会计期");
        columns2.setDataType("S");
        listCol.add(columns2);
        Columns columns3=new Columns();
        columns3.setName("RETURN_TIME");
        columns3.setCaption("反馈时间");
        columns3.setDataType("S");
        listCol.add(columns3);
        Columns columns4=new Columns();
        columns4.setName("MSG_TYPE");
        columns4.setCaption("消息类型(S:成功 ;E:失败)");
        columns4.setDataType("S");
        listCol.add(columns4);
        Columns columns5=new Columns();
        columns5.setName("MESSAGE");
        columns5.setCaption("消息内容");
        columns5.setDataType("S");
        listCol.add(columns5);
        Columns columns6=new Columns();
        columns6.setName("SYSTEM_ID");
        columns6.setCaption("系统别");
        columns6.setDataType("S");
        listCol.add(columns6);
        table.setListCol(listCol);
        List<Rows> listRow=new ArrayList<Rows>();
        Rows rows=new Rows();
        rows.setMessage("消息接收成功");
        rows.setAccountPeriod("202307");
        rows.setMsgType("S");
        rows.setMrLineId("BJJHGG01230700032-001");
        rows.setReturnTime("20230711153319");
        rows.setSystemId("1012");
        listRow.add(rows);
        table.setListRows(listRow);
        listTab.add(table);
        iXbusPlanInfoBuild.setMessageHeader(messageHeader);
        iXbusPlanInfoBuild.setListTab(listTab);
        return iXbusPlanInfoBuild;
    }
}

关闭

用微信“扫一扫”