如何寫一個巢狀實體類,賦值,轉化為JSON格式的字串
import java.io.Serializable;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
//通過Serializable的toString方法,將類轉變為json字串
public class AwardPara implements Serializable {
private String merchantId;
private String sn;
private String timestamp;
private Body body;//內部類
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
//注意內部類的set方法
public Body getBody() {
return body;
}
//內部類通過內部類的構造器和set方法進行賦值
public void setBody(String issue,String lotoId) {
this.body = new Body(issue,lotoId);
}
//外部引數通過構造器賦值
public AwardPara(String merchantId, String sn,String timestamp) {
this.merchantId = merchantId;
this.sn = sn;
this.timestamp = timestamp;
}
public static class Body implements Serializable {
private String issue;
private String lotoId;
//內部類的構造器
public Body (String issue,String lotoId){
this.issue = issue;
this.lotoId = lotoId;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getLotoId() {
return lotoId;
}
public void setLotoId(String lotoId) {
this.lotoId = lotoId;
}
}
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}
2、下面是如何呼叫該實體類並賦值
//實體類外部引數賦值
AwardPara awardPara = new AwardPara(merchantId,"01201605311237390001","2017");
//實體類的內部類賦值
awardPara.setBody("2017077", "101");
//將實體類轉換為json字串,
String para = awardPara.toString();
3、得到的para的結果如下
{"body":{"issue":"2017077","lotoId":"101"},"merchantId":"0029","sn":"01201605311237390001","timestamp":"2017"}