Java中的对象转JSON和JSON转对象

476 阅读1分钟

先说结论吧: 使用阿里的fastjson包,就可以很方便的相互转换。pom引入

 <!--工具类-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
</dependency>

下面是具体的例子:

  • 实体类ReqCheckAccount继承ReqMain,ReqMain中只有几个通用的属性。下面直接贴ReqCheckAccount类
public class ReqCheckAccount extends ReqMain {


    private String account = "";//账户
    private String accountName = "";//账户户名

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    @Override
    public String toString() {
        return "ReqCheckAccount{" +
                "account='" + account + '\'' +
                ", accountName='" + accountName + '\'' +
                ", id='" + id + '\'' +
                ", appId='" + appId + '\'' +
                ", bankId='" + bankId + '\'' +
                ", jgxybh='" + jgxybh + '\'' +
                '}';
    }
}
  • 测试类 这里用的是Test(org.junit.jupiter.api.Test)注解,直接创建一个test类,用test注解即可:
@Test
    public void testJSON(){
        ReqCheckAccount reqCheckAccount = new ReqCheckAccount();
        String strJson = JSONObject.toJSONString(reqCheckAccount);
        System.out.println("Object to JSON test:"+strJson);

        strJson = "{\"account\":\"111\",\"accountName\":\"222\",\"appId\":\"333\",\"bankId\":\"444\",\"id\":\"555\",\"jgxybh\":\"666\"}";
        ReqCheckAccount reqObj = (ReqCheckAccount) JSONObject.toJavaObject(JSON.parseObject(strJson),ReqCheckAccount.class);
        System.out.println("JSON to Object:"+reqObj.toString());
    }

结果

image.png