对于具有以下注释的Java代码:
devDependencies
将对象用于GET时的结果集是:
@JsonProperty(value="Contact")
@NotNull(message = "ContactUser or CompanyName is required.")
@Valid
@XmlElements(value = {
@XmlElement(name = "ContactUser", type = ContactUser.class, required = true),
@XmlElement(name = "CompanyName", type = String.class, required = true) })
private Object contactInfo;
或
"Contact":{
"ContactUser":{
"Title": "Miss",
"LastName": "Hello"
}
}
有没有办法让它返回:
"Contact": "Hello Company"
或
"ContactUser":{
"Title": "Miss",
"LastName": "Hello"
}
代替?在xml中,使用代码,您可以执行以下操作:
"CompanyName": "Hello Company"
或
<CompanyName>Hello Company</CompanyName>
我尝试过使用JsonTypeInfo,但它似乎没有处理String.class:
<ContactUser>
<Title>Miss</Title>
<LastName>Hello</LastName>
</ContactUser>
答案 0 :(得分:0)
{
"ContactUser" : {
"Title" : "sampleTitle",
"LastName" : "sampleLastName"
},
"CompanyName" : "XXXXX"
}
你能改一下你的问题吗?我想我完全不明白你的意图是什么。
这是我的代码:
@JsonProperty(value = "Contact")
@XmlElements(value = {
@XmlElement(name = "ContactUser", type = ContactUser.class, required = true)
,
@XmlElement(name = "CompanyName", type = String.class, required = true)})
private Object contactInfo;
public TestClassConstructor() throws JsonProcessingException {
contactInfo = new HashMap<String, Object>();
((HashMap) contactInfo).put("ContactUser", new ContactUser("sampleTitle", "sampleLastName"));
((HashMap) contactInfo).put("CompanyName", "XXXXX");
ObjectMapper mapper = new ObjectMapper();
String jsonResult = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(contactInfo);
System.err.println(jsonResult);
}
如果您想要特定的序列化程序,则需要检查:http://www.baeldung.com/jackson-serialize-field-custom-criteria