[英]Convert only few JSON fields to API object
In the JSON reponse that an API gives me back, i have more than 100 fields, but am interested in only 3 fields.在 JSON 回复 API 给我的回复中,我有 100 多个字段,但我只对 3 个字段感兴趣。 For example, if below is the full JSON response
例如,如果下面是完整的 JSON 响应
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
I want only 3 fields我只想要 3 个字段
"data": "Click Here",
"size": 36,
"style": "bold"
This is my response object in ArunApi.java would look like这是我在 ArunApi.java 中的响应object看起来像
private String data;
private Integer size;
private String style;
When i make a REST Call (below is the snippet), it fails当我拨打 REST 电话(下面是代码片段)时,它失败了
var response = webClient
.get()
.uri(endPoint)
.retrieve()
.bodyToMono(ArunApi.class)
.block();
Since i have only 3 fields in my API, the conversion isn't happening at all.由于我的 API 中只有 3 个字段,因此根本没有进行转换。 Please help
请帮忙
You can annotate your class with @JsonIgnoreProperties(ignoreUnknown = true)
if you are using Jackson library.如果您使用的是 Jackson 库,则可以使用
@JsonIgnoreProperties(ignoreUnknown = true)
注释您的 class。 Otherwise, depending on which library you are using, you can search for configuration to ignore fields.否则,根据您使用的库,您可以搜索配置以忽略字段。
https://github.com/FasterXML/jackson-annotations https://github.com/FasterXML/jackson-annotations
You can parse the whole JSON string with GenSON.您可以使用 GenSON 解析整个 JSON 字符串。 With the function
parseKeys()
you can get a HashMap that contains all the keys and extract the first three.使用 function
parseKeys()
您可以获得包含所有密钥的 HashMap 并提取前三个。 GenSON is a new library that I created because of problems similar to yours. GenSON 是我创建的一个新库,因为与您的问题类似。 Link: https://github.com/EvgeniGenchev/GenSON-lib .
链接: https://github.com/EvgeniGenchev/GenSON-lib 。
You can try to use an abstract class with JsonTypeInfo and JsonSubTypes annotations to receive the data and then map with any thing subclass you need.您可以尝试使用带有 JsonTypeInfo 和 JsonSubTypes 注释的抽象 class 来接收数据,然后将 map 与您需要的任何事物子类一起使用。 For example:
例如:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = RecurringTriggerJsonModel.class, name = "RECURRING"),
@JsonSubTypes.Type(value = SimpleTriggerJsonModel.class, name = "SIMPLE"),
@JsonSubTypes.Type(value = CronTriggerJsonModel.class, name = "CRON")
})
public abstract class TaskTriggerJsonModel {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.