我在我的项目中使用声明性链接。我的 jackson 映射器配置是
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
mapper.configure(MapperFeature.AUTO_DETECT_FIELDS, false);
mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
由于我禁用了任何类型的自动检测,注入(inject)的链接如
@InjectLinks({
@InjectLink(rel = "bookmark", resource = ConnectionsResource.class, style = Style.ABSOLUTE_PATH) })
@JsonProperty("links")
Link[] links;
被序列化为空的 JSON 对象(因为“Link”中的任何字段都没有使用 @JsonProperty
进行注释)。
如何在不更改全局映射器配置的情况下仅对字段 rel
和 href
启用链接序列化?
最佳答案
因此,实现此目的的一种方法是使用客户序列化程序。您必须为此序列化程序添加一个新模块到ObjectMapper
,但这不应影响其余配置。
这是序列化器
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import javax.ws.rs.core.Link;
public class LinkSerializer extends JsonSerializer<Link>{
@Override
public void serialize(Link link, JsonGenerator jg, SerializerProvider sp)
throws IOException, JsonProcessingException {
jg.writeStartObject();
jg.writeStringField("rel", link.getRel());
jg.writeStringField("href", link.getUri().toString());
jg.writeEndObject();
}
}
这里是一个测试类
public class TestClass {
@JsonProperty("links")
protected List<Link> links;
protected String name;
protected String id;
// getter and setters
}
以及测试运行
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
mapper.configure(MapperFeature.AUTO_DETECT_FIELDS, false);
mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Link.class, new LinkSerializer());
mapper.registerModule(simpleModule);
Link link1 = Link.fromUri(URI.create("http://localhost:8080/")).rel("one").build();
Link link2 = Link.fromUri(URI.create("http://localhost:8080/")).rel("two").build();
TestClass test = new TestClass();
test.getLinks().add(link1);
test.getLinks().add(link2);
String json = mapper.writeValueAsString(test);
System.out.println(json);
}
产生这个结果
{
"links" : [ {
"rel" : "one",
"href" : "http://localhost:8080/"
}, {
"rel" : "two",
"href" : "http://localhost:8080/"
} ]
}
希望这有帮助。
关于java - 如何使用 Jackson 序列化声明性链接( Jersey ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26989004/