簡體   English   中英

在SPRING REST中對父類的響應

[英]Response with the parent class in SPRING REST

我已經使用Jackson實施了帶有SPRING REST的REST API(在pom.xml中使用org.codehaus.jackson包-jackson-mapper-asl-1.9.13指定)。 在控制器中,我有:

@Controller
@RequestMapping("/test")
public class TestController {
    @RequestMapping(value="id", method= RequestMethod.GET)
    @ResponseBody
    public Parent findById(@PathVariable("id") int id) {
       Child child = new Child();
       child.setId(id);
       child.setName("test");
       return child;
    }
}

例如在父級中,我們可以有:

public class Parent {
    int id;

    public void setId(int id) {
        this.id = id;
    }
}

和孩子:

public class Child extend Parent {
    String name;

    public void setName(String name) {
        this.name = name;
    }
}

我的問題是我希望響應僅與父類一起而不與子類一起使用(因為現在響應具有子結構)。

以下是一種適合您的解決方案:

@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class Parent {

    @JsonProperty
    int id;

    public void setId(int id) {
        this.id = id;
    }
}

我必須承認,這種解決方案並不是十分@JsonProperty因為您需要在Parent類的每個字段中添加@JsonProperty批注,但是這樣做的好處是無需對其任何子類進行修改

可以在這里找到jackson庫中存在的所有注釋。

@JsonAutoDetect的Javadoc可以在這里找到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM