英文:
Configure Spring Boot to receive only required JSON data
问题
当你连接到一个API并接收一个对象作为回应时,我过去常做的是创建一个与该对象匹配的POJO,然后填充数据。有时API提供了数百个字段,而我并不需要所有这些字段,因此我不得不创建大型的POJO,包括子POJO等。显然,你可以设置Spring Boot,以便只接收你需要的部分。但是我似乎无法弄清楚如何设置,也找不到一个解释这个问题的教程。
我如何设置Spring Boot,以便我可以接收来自API的JSON数据,但只包括我需要的属性,而不是整个对象?
我不想不得不创建一个完整的POJO,类似于这样:
class Receive {
属性1;
属性2;
属性3;
属性4;
属性5;
属性6;
//等等
}
而是设置它,以便我只需创建我需要接收的部分,例如:
class Receive {
属性4;
属性10;
}
英文:
When you connect to an api and receive an object as an answer. What I used to do is create a pojo that matches the object, and than let de data be filled in. Sometimes the api provides hundreds of fields that I don't need, and I have to create giant pojos, with subpojos etc.. Apparently you can set up Spring Boot so that you only need to receive the part you want want. But I cannot seem to figure out how, nor can I find a tutorial somewhere where it is explained.
How can I set up Spring Boot so I can receive the JSON data from an api, but only the attributes I need, not the entire object?
I don't want to have to make an entire pojo like this:
class Receive {
attribute 1;
attribute 2;
attribute 3;
attribute 4;
attribute 5;
attribute 6;
//and so forth
}
but set it up so I only have to make what I need to receive, for example:
class Receive {
attribute 4;
attribute 10;
}
答案1
得分: 1
你可以在服务器端不进行任何操作,但可以在模型中定义你想要处理的字段,并在类级别上设置以下注解(以忽略其他字段):
@JsonIgnoreProperties(ignoreUnknown = true)
英文:
You can't do anything on the Server side but you can define in your model the fields you want to deal with and set on Class level following annotation(to ignore the rest of the fields )
@JsonIgnoreProperties(ignoreUnknown = true)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论