我尝试了几种使用java创建以下格式json的方法。 (Gson,Jackson,......)
{
"outbound": {
"address": [
"t91",
"t0992"
],
"send": "t678",
"outMessage": {
"message": "Hello World"
},
"client": "156",
"receipt": {
"URL": "http://example.com/Delivery",
"callback": "some-to-the-request"
},
"senderName": "Inc."
}
}
任何帮助?
答案 0 :(得分:1)
使用以下代码。 创建POJO
public class TestPojo {
private Outbound outbound;
public Outbound getOutbound() {
return outbound;
}
public void setOutbound(Outbound outbound) {
this.outbound = outbound;
}
}
class Outbound {
private String[] address;
private String send;
private OutMessage outMessage;
private Receipt receipt;
private String senderName;
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public OutMessage getOutMessage() {
return outMessage;
}
public void setOutMessage(OutMessage outMessage) {
this.outMessage = outMessage;
}
public Receipt getReceipt() {
return receipt;
}
public void setReceipt(Receipt receipt) {
this.receipt = receipt;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
}
class OutMessage {
private String message;
public OutMessage(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class Receipt {
private String URL;
private String callback;
public Receipt(String uRL, String callback) {
super();
URL = uRL;
this.callback = callback;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
}
主类(JSON到对象)
String json = "{'outbound':{'address':['t91','t0992'],'send':'t678','outMessage':{'message':'Hello World'},'receipt':{'URL':'http://example.com/Delivery','callback':'some-to-the-request'},'senderName':'Inc.'}}";
TestPojo testPojo = new Gson().fromJson(json, TestPojo.class);
System.out.println(testPojo.getOutbound().getSenderName());
<强>输出强>
Inc.
主类(对象为JSON)
TestPojo testPojo = new TestPojo();
Outbound outbound = new Outbound();
outbound.setAddress(new String[]{"t91", "t0992"});
outbound.setOutMessage(new OutMessage("Hello World"));
outbound.setReceipt(new Receipt("http://example.com/Delivery", "some-to-the-request"));
outbound.setSenderName("Inc.");
outbound.setSend("t678");
testPojo.setOutbound(outbound);
System.out.println(new Gson().toJson(testPojo));
<强>输出强>
{"outbound":{"address":["t91","t0992"],"send":"t678","outMessage":{"message":"Hello World"},"receipt":{"URL":"http://example.com/Delivery","callback":"some-to-the-request"},"senderName":"Inc."}}
<强>详细强>
使用过的GSON库。 使用了你给的json。