[英]How to customize Spring Rest Controller errors with Jackson or malformed request
[英]How to request only necessary fields using Spring and Jackson in a REST architecture?
因此,在我們的項目中,我們使用@JsonView來排除我們在每個請求中不希望被序列化/調用的屬性。 問題是這非常粗糙,我們需要在每次需要不同的東西時在模型上創建一個新的View或annotate,遵循這個例子: 非常好的人有博客 。 我們認為這不是真正優化的,並且是一種非常好的樣板方式,因此我們希望改變這種邏輯:而不是服務器只響應它想要的,我們想要請求服務器只響應什么客戶希望從服務器移動該責任。 我沒有做一個簡單的$ .get,而是將$ .get的參數傳遞給我想要的屬性(即只有名稱和圖片,有時候是完整的信息用於編輯等)。 我知道這是可能的,但我還沒有找到任何使用Spring的方法。 我們正在使用Spring 4.2和Jackson 2.6.1並使用AngularJS來使用REST,所以這真的有幫助。 有關如何做到這一點或任何指導的任何想法? 非常感謝你的幫助!
GET請求:
{
username,
picture
}
並收到json響應:
{
"id":1,
"username":"john",
"picture":"/john.png"
}
沿着這些方向的東西。
如果序列化/反序列化策略不起作用,那么您應該考慮使用構建器。 開發你想要的東西將是非常直接的,但沒有魔力。 一些替代方案: https : //github.com/ralfstx/minimal-json,http : //www.javabeat.net/java-json-api-jsr-353/,https : //github.com/Homyk/JsonBuilder/ wiki / JsonBuilder-WIKI 。
我也需要類似的實現,並使用傑克遜這樣做。 我使用自定義序列化器和java反射。 不需要更改模型類。
// my sample object
public class A {
private int _1;
private int _2;
private int _3;
public A(int _1, int _2, int _3) {
this._1 = _1;
this._2 = _2;
this._3 = _3;
}
.. getters .. setters
}
我班的自定義序列化器。
public class ASerializer extends JsonSerializer<A> {
private final List<String> properties;
public ASerializer(String... properties) {
this.properties = Arrays.asList(properties);
}
@Override
public Class<A> handledType() {
return A.class;
}
@Override
public void serialize(A a, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
/* wanted property list is provided through constructor of serializer */
for (String property : this.properties) {
try {
/* field values are accessed by reflection */
Field field = a.getClass().getDeclaredField(property);
field.setAccessible(true);
Object value = field.get(a);
jgen.writeObjectField(property, value);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(ASerializer.class.getName()).log(Level.SEVERE, null, ex);
}
}
jgen.writeEndObject();
}
}
用法:
public class App {
public static void main(String... args) throws JsonProcessingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
/* initialize object */
A a = new A(1, 2, 3);
/* initialize a new serializer object with wanted properties and add to module */
module.addSerializer(new ASerializer(new String[]{"_1", "_2"}));
/* if you want to flush cached serializers */
DefaultSerializerProvider dsp = (DefaultSerializerProvider) objectMapper.getSerializerProvider();
dsp.flushCachedSerializers();
objectMapper.registerModule(module);
System.out.println(objectMapper.writeValueAsString(a));
}
}
輸出:
{"_1":1,"_2":2}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.