Java 如何使用Jackson将POJO转换为XML
我正在寻找最好的解决方案,如何将POJO或JSON转换为XML,并将所有属性放在正确的位置。目前,杰克逊似乎是最方便的方式。我能够在没有属性的情况下将POJO序列化为XML POJO测试用户Java 如何使用Jackson将POJO转换为XML,java,xml,json,jackson,pojo,Java,Xml,Json,Jackson,Pojo,我正在寻找最好的解决方案,如何将POJO或JSON转换为XML,并将所有属性放在正确的位置。目前,杰克逊似乎是最方便的方式。我能够在没有属性的情况下将POJO序列化为XML POJO测试用户 public class TestUser extends JsonType { @JsonProperty("username") private final String username; @JsonProperty("fullname") private final
public class TestUser extends JsonType
{
@JsonProperty("username")
private final String username;
@JsonProperty("fullname")
private final String fullname;
@JsonProperty("email")
private final String email;
@JsonProperty("enabled")
private final Boolean enabled;
@JsonCreator
public TestUser(
@JsonProperty("username") String username,
@JsonProperty("fullname") String fullname,
@JsonProperty("email") String email,
@JsonProperty("enabled") Boolean enabled)
{
this.username = username;
this.fullname = fullname;
this.email = email;
this.enabled = enabled;
}
@JsonGetter("username")
public String getUsername()
{
return username;
}
@JsonGetter("fullname")
public String getFullname()
{
return fullname;
}
@JsonGetter("email")
public String getEmail()
{
return email;
}
@JsonGetter("enabled")
public Boolean getEnabled()
{
return enabled;
}
}
}
代码如下:
public void testJsonToXML() throws JsonParseException, JsonMappingException, IOException
{
String jsonInput = "{\"username\":\"FOO\",\"fullname\":\"FOO BAR\", \"email\":\"foobar@foobar.com\", \"enabled\":\"true\"}";
ObjectMapper jsonMapper = new ObjectMapper();
TestUser foo = jsonMapper.readValue(jsonInput, TestUser.class);
XmlMapper xmlMapper = new XmlMapper();
System.out.println(xmlMapper.writer().with(SerializationFeature.WRAP_ROOT_VALUE).withRootName("product").writeValueAsString(foo));
}
现在它返回这个
<TestUser xmlns="">
<product>
<username>FOO</username>
<fullname>FOO BAR</fullname>
<email>foobar@foobar.com</email>
<enabled>true</enabled>
</product>
</TestUser>
我发现了一些使用@JacksonXmlProperty
的示例,但它只向根元素添加属性
感谢您的帮助有趣的问题:附加数据的注入。目前没有这样做的功能;但我认为可以在
@JsonRootName
(schema=URL
?)中添加一个新属性,允许添加一个或多个模式映射
我继续写了这封信:
添加一些应该有效的内容;请随意添加评论和建议。您在
TestUser
中扩展的JsonType
的完整包名是什么?
<TestUser xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="testUser.xsd">
<product>
<username enabled="true">FOO</username>
<fullname>FOO BAR</fullname>
<email>foobar@foobar.com</email>
</product>
</TestUser>