gpt4 book ai didi

Java Spring MVC & Jackson : get only selected variables from entities

转载 作者:行者123 更新时间:2023-12-01 12:40:04 26 4
gpt4 key购买 nike

我有三个实体 HelloWorld (和 Abc ):

import org.codehaus.jackson.annotate.JsonIgnore;
@Entity
@Table(name="hello")
public class Hello implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private int id;

@Column(nullable=false, unique=true)
private Integer address;

@ManyToOne
@JoinColumn(name="world_id", nullable=false)
private World world;

@OneToMany(mappedBy="abc")
@JsonIgnore
private List<Abc> abc;
}

@Entity
@Table(name="world")
public class World implements Serializable {

@Id
@Column(unique=true, nullable=false)
private int id;

@Column(nullable=false, unique=true)
private String address;

@OneToMany(mappedBy="world")
private List<Hello> hello;
}

在 Spring Controller 中我有:

@RequestMapping(value="/json/world/get/all", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<World> getWorlds() {
return worldManager.findAll();
}

如果我转到映射的 URL,我会得到类似的 JSON:

[  
{
"id":1,
"address":123456,
"world":{
"id":1,
"address":"192.168.200.1"
}
},
{
"id":2,
"address":123457,
"world":{
"id":1,
"address":"192.168.200.1"
}
},
...
}
]

List<Abc> 不在 JSON 中 - 没关系,但它有 @JsonIgnore 。但我不希望在 此 Controller URLworld 输出中使用 hello objectcs,在另一个 URL 上我需要 helloworld

我怎样才能做到这一点?比如动态添加/删除注释。

我尝试了 jackson 的观点,但它不起作用 - 我做得很糟糕:-(

如何在 Controller 中编写两个方法 - 第一个方法将返回包含所有 hello 对象的 world,第二个方法将仅返回包含所有 hello 对象的 world

最佳答案

Jackson 在类级别有一个名为 @JsonSerialize(include = Inclusion.NON_NULL) 的注释。此注释意味着如果变量为 null,Jackson 将不会输出任何内容。在 Controller 中,您可以在返回之前将不想发送的值设置为 null。像这样的事情:

修改Bean:

@Entity
@Table(name="world")
@JsonSerialize(include = Inclusion.NON_NULL) //New Line!!!
public class World implements Serializable {
...
...
}

有两个 Controller :

@RequestMapping(value="/json/world/get/all", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<World> getWorlds() {
return worldManager.findAll();
}


@RequestMapping(value="/json/world/get/all2", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<World> getWorldsWithOutHellos() {
List<World> result = worldManager.findAll();
for (World world:result){
world.setHello(null);
}
return result;
}

关于Java Spring MVC & Jackson : get only selected variables from entities,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25194535/

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