目前我的代码正在接收带有
主体的POST请求{
"EventBody": {
"message":"{\"sysData\":{\"time\":1520865496235,\"data\":{\"appUUID\":\"randomnumber\",\"userId\":\"1801\"}},\"appData\":{\"testMessage\":\"Stuff to see\",\"ackURL\":\"http:localhost/generic\"\"}}",
"client": {
"device": {
"device-id": 12345
}
}
}
}
如果被转换为这样的pojo对象,该身体
@JsonIgnoreProperties(ignoreUnknown = true)
public class EventBody {
// If state message object as type string I do get the string, if
// I keep it GenericMessage object I am met with a null object.
@JsonProperty("message")
public GenericMessage message;
@JsonIgnoreProperties(ignoreUnknown = true)
public class GenericMessage {
@JsonProperty("sysData")
public SysData sysData;
@JsonProperty("appData")
public AppData appData;
public class SysData {
public String time;
public Data data;
public class Data {
public String appUUID;
public Integer userId;
}
}
public class AppData {
public String ackURL;
}
}
@JsonProperty("client")
public Client client;
public class Client {
@JsonProperty("device")
public Device device;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Device {
@JsonProperty("device-id")
public Integer deviceId;
}
}
}
我遇到了如何解析格式化为JSON对象的/ delimited字符串的问题。通过将GenericMessage类移动到它自己的单独类中并由服务类用于使用此方法解析它,我已经有了它的工作。
public GenericMessage convertGenericMessage(String message) throws MessageException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
if(message != null) {
GenericMessage foundMessage = objectMapper.readValue(message, GenericMessage.class);
return foundMessage;
} else {
throw new MessageException("Message field empty in event Object");
}
} catch (Exception e) {
throw new MessageException("Exception while converting message to GenericMessage object: " + e.getMessage());
}
}
但这有点难看并引入了我希望不必要的额外步骤。有没有办法为GenericMessage调用某种隐式构造函数,以便解析JSONString对象?