我面临的情况是REST服务需要XML请求,需要将请求中的数据存储到数据库中。请求XML基本上给出了需要持久化的类的值。
例如,假设我需要按如下方式保持一个类:
@Entity
public class Person {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
}
请求XML可能如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<PersonInputs>
<Input type="String" name="firstName">Foo</Input>
<Input type="String" name="lastName">Bar</Input>
</PersonInputs>
我是否可以使用JAXB注释创建Person
对象并以简单的方式绑定请求XML中的数据?我暂时不熟悉JAXB,所以我希望能得到一些明智的建议。尽管如此,我们非常感谢任何意见。
答案 0 :(得分:1)
您可以将此解决方案与其他课程Input
@XmlAccessorType(XmlAccessType.FIELD)
public class Input
{
@XmlAttribute
private String type;
@XmlAttribute
private String name;
@XmlValue
private String value;
public Input() {}
public Input(String type, String name, String value)
{
this.type = type;
this.name = name;
this.value = value;
}
}
实体中的其他吸气剂 变体1
@XmlRootElement(name= "PersonInputs")
@XmlAccessorType(XmlAccessType.NONE)
public class Person
{
@Id @GeneratedValue
private Long id;
private String firstName = "foo";
private String lastName = "bar";
// getters/setters
@XmlElement(name= "Input")
Input getFirstNameXML()
{
return new Input(String.class.getSimpleName(), "firstName", firstName);
}
@XmlElement(name= "Input")
Input getLastNameXML()
{
return new Input(String.class.getSimpleName(), "lastName", lastName);
}
}
变体2
@XmlRootElement(name= "PersonInputs")
@XmlAccessorType(XmlAccessType.NONE)
public class Person
{
private Long id;
private String firstName = "foo";
private String lastName = "bar";
// getters/setters
@XmlElement(name = "Input")
List<Input> getList() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException
{
return getInputs(this, "firstName", "lastName"); // fields names
}
}
Util方法getInputs
static List<Input> getInputs(Object thisObj, String ... fields) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException
{
final List<Input> retVal = new ArrayList<Input>();
for (String field : fields)
{
Field f = thisObj.getClass().getDeclaredField(field);
f.setAccessible(true);
retVal.add(new Input(f.getType().getSimpleName(), field, (String )f.get(thisObj)));
}
return retVal;
}