龙空技术网

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

烧烧果实ss 91

前言:

现在我们对“java读json文件转换为对象”可能比较关注,你们都想要了解一些“java读json文件转换为对象”的相关知识。那么小编在网上收集了一些对于“java读json文件转换为对象””的相关内容,希望大家能喜欢,各位老铁们一起来学习一下吧!

先说结论吧: 使用阿里的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    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());    }
结果

输出结果

标签: #java读json文件转换为对象