有一个课程如下 -
public class Org{
@XmlElementRef(name = "InstitutionCode", namespace = "http://schemas.tes.org/2004/07/ABC.test", type = JAXBElement.class, required = false)
protected JAXBElement<String> institutionCode;
}
使用Jackson将对象组织转换为JSON
ObjectMapper mapper = new ObjectMapper();
JAXBElement<String> code =
new JAXBElement<String>(new QName("http://schemas.tes.org/2004/07/ABC.test", "institutionCode"), String.class, "inst");
Organization org = new Organization();
org.setInstitutionCode(code);
String jsonInString = mapper.writeValueAsString(org);
System.out.println(jsonInString);
获取值
{"institutionCode":{"Name":"{http://schemas.tes.org/2004/07/ABC.test}institutionCode"}
如何获取值
{"institutionCode":"inst"}
谢谢,
答案 0 :(得分:1)
您可以为它编写自定义的Jackson序列化程序:
public class OrgSerializer extends JsonSerializer<Org> {
@Override
public void serialize(Org org, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("institutionCode", org.getInstitutionCode());
jgen.writeEndObject();
}
}
然后,您可以注释该类以使用序列化程序:
@JsonSerialize(using = OrgSerializer.class)
public class Org {
// ...
}
或者,如果您不希望每次都这样,或者您无法更改类,则可以将该类作为参数传递给ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Org.class, new OrgSerializer());
mapper.registerModule(module);
另一个解决方案是使用@JsonView
,但我自己没有使用过。