我有以下JSON,我想将其转换为Java POJO。
我使用com.fasterxml.jackson.databind.ObjectMapper
作为对象。
{
"deviceType":"firefox",
"devices":{
"device#1234":{
"userName":"pcp",
"rowId":12345
}
},
"serviceId":12345,
"message":{
"alert":"Hi, I am alert"
}
}
Java POJO Class
public class TestDevices extends App {
private String message;
private JSONObject devices;
private List<String> deviceKeys;
private String deviceType;
private String campaignId;
public TestDevices() {
// To make reflection happy
}
public TestDevices(long serviceId) {
super(serviceId);
}
public TestDevices(long serviceId, String message, JSONObject devices, List<String> deviceKeys, String deviceType) {
super(serviceId);
this.message = message;
this.devices = devices;
this.deviceKeys = deviceKeys;
this.deviceType = deviceType;
}
public String getCampaignId() {
return campaignId;
}
public void setCampaignId(String campaignId) {
this.campaignId = campaignId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public JSONObject getDevices() {
return devices;
}
public void setDevices(JSONObject devices) {
this.devices = devices;
}
public List<String> getDeviceKeys() {
return deviceKeys;
}
public void setDeviceKeys(List<String> deviceKeys) {
this.deviceKeys = deviceKeys;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
@Override
public String toString() {
return "Device [message=" + message + ", devices=" + devices + ", deviceKeys=" + deviceKeys + ", deviceType="
+ deviceType + ", serviceId=" + serviceId + "]";
}
}
我的杰克逊召集人
public static TestDevices buildMockObject(String payload)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.AUTO_CLOSE_SOURCE, true);
TestDevices devices = mapper.readValue(payload, TestDevices.class);
return devices;
}
但我收到此错误:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "device#1234" (class org.json.JSONObject), not marked as ignorable (0 known properties: ])
at [Source: {"deviceType":"firefox","devices":{"device#1234":{"userName":"pcp","rowId":12345}},"serviceId":12345,"message":{"alert":"Hi, I am alert"}}; line: 1, column: 51] (through reference chain: com.shephertz.karma.TestDevices["devices"]->org.json.JSONObject["device#1234"])
注意:
我上面给出的json中的devices
和message
个键包含具有动态键的json对象。
由于错误说它无法将JSON字段解析为我的java类。 我做错了什么以及如何解决上述错误?