gpt4 book ai didi

Java Spring Web 序列化子类的属性

转载 作者:行者123 更新时间:2023-12-02 10:33:59 25 4
gpt4 key购买 nike

我有一个 Maven Java Spring Rest 项目,我想在其中执行此操作。

@RestController
@RequestMapping("/person")
public class PersonController {
@GetMapping
public List<Person> getPerson(){

List<Person> persons = new ArrayList<>();

persons.add(new Dev(1, "Java")); //Let's say I have the constructor
persons.add(new DevOps(2, "Linux")); //Let's say I have the constructor

return implants;
}
}

public class Person{ public int id;}

public class Dev extends Person{ public string lang;}

public class DevOps extends Person{ public string env;}

我希望结果是

[

{id : 1, lang: "Java"},//<- 这是开发

{id : 2, env: "Linux"},//<- 这是 DevOps

]

不仅仅是

[

{id : 1},//<- 这是开发

{id : 2},//<- 这是 DevOps

]

最佳答案

尝试重现您的问题,但没有成功:

@RestController
@RequestMapping("/person")
public class PersonController {

@GetMapping
public List<Person> getPerson(){
List<Person> persons = new ArrayList<>();

persons.add(new Dev(1, "Java")); //Let's say I have the constructor
persons.add(new DevOps(2, "Linux")); //Let's

return persons;
}
}

public class Person {
public int id;

public Person(int id) {
this.id = id;
}
}

public class Dev extends Person {
public String lang;

public Dev(int id, String lang) {
super(id);
this.lang = lang;
}
}

public class DevOps extends Person {
public String env;

public DevOps(int id, String env) {
super(id);
this.env = env;
}
}

结果:

http://localhost:8080/person/

[{"id":1,"lang":"Java"},{"id":2,"env":"Linux"}]

您确定您发布了所有相关代码吗?既然您说过假设我有构造函数,我只能假设您正确创建了它们。

关于Java Spring Web 序列化子类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com