对于带有以下注释的 Java 代码:
@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;
当我使用对象进行 GET 时的结果集是:
"Contact": {
"ContactUser": {
"Title": "Miss",
"LastName": "Hello"
}
}
或
"Contact": "Hello Company"
有没有办法让它返回:
"ContactUser": {
"Title": "Miss",
"LastName": "Hello"
}
或
"CompanyName": "Hello Company"
相反?在 xml 中,使用代码,您可以:
<CompanyName>Hello Company</CompanyName>
或
<ContactUser>
<Title>Miss</Title>
<LastName>Hello</LastName>
</ContactUser>
我尝试过使用 JsonTypeInfo,但它似乎无法处理 String.class:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include =JsonTypeInfo.As.WRAPPER_OBJECT, visible=true)
@JsonSubTypes({
@JsonSubTypes.Type(name = "ContactUserJ", value = ContactUser.class),
@JsonSubTypes.Type(name = "CompanyNameJ" , value = String.class)
})
最佳答案
你在用 Spring 吗?我使用了一个简单的 java 类在简单的 java 中我得到了
{
"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
关于java - Json 版本的 XMLElements 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48279720/