我在C#中有一个如下所示的课程,
class Person
{
List<String> hobbies;
}
当我使用Jaxb将其转换为Java类时,它看起来像
class Person
{
@XmlElement(name = "hobbies")
ArrayOfString hobbies;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfString", propOrder = {
"string"
})
public class ArrayOfString {
@XmlElement(nillable = true)
protected List<String> string;
}
到目前为止一切都很好,但是现在,当我尝试使用Jackson Objectmapper将此对象转换为Json时,
ObjectMapper mapper = new ObjectMapper();
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String jsonString= ow.writeValueAsString(Person);
我得到如下的json输出,
{
"hobbies" : { "string" : [ "reading","writing"] }
}
现在,我需要json如下所示,没有string关键字。
{
"hobbies" : [ "reading","writing"]
}
不幸的是,我无法更改c#生成的xsd。 有什么办法吗?
答案 0 :(得分:0)
不确定您的JAXB部分,但是如果您将bean类定义为:
class Person
{
private ArrayOfString hobbies;
public ArrayOfString getHobbies() {
return hobbies;
}
public void setHobbies(ArrayOfString hobbies) {
this.hobbies = hobbies;
}
}
class ArrayOfString {
@JsonValue
protected List<String> string;
public List<String> getString() {
return string;
}
public void setString(List<String> string) {
this.string = string;
}
}
请注意字段@JsonValue
上的注释protected List<String> string
。
现在您将获得预期的结果。
public static void main(String[] args) throws JsonProcessingException {
Person person = new Person();
person.hobbies = new ArrayOfString();
person.hobbies.string = Arrays.asList("reading","writing");
ObjectMapper mapper = new ObjectMapper();
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String jsonString= ow.writeValueAsString(person);
System.out.println(jsonString);
}
输出
{
"hobbies" : [ "reading", "writing" ]
}
注意:您仍然可以在bean上添加JAXB注释,而没有副作用。