先说结论吧: 使用阿里的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) { = account; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { Name = 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); Sy("Object to JSON test:"+strJson); strJson = "{\"account\":\"111\",\"accountName\":\"222\",\"appId\":\"333\",\"bankId\":\"444\",\"id\":\"555\",\"jgxybh\":\"666\"}"; ReqCheckAccount reqObj = (ReqCheckAccount) JSONObject.toJavaObjec(strJson),ReqC); Sy("JSON to Object:"+reqObj.toString()); }
- 结果
输出结果