[英]How to do a specific operation to only certain fields in a Java object or a JSON payload
I have a spring boot microservices application and within it, I want to do a specific operation (say some string manip) on specific fields of a Java object (or a JSON object). 我有一个spring boot microservices应用程序,在其中,我想对Java对象(或JSON对象)的特定字段执行特定的操作(例如一些字符串操作)。
For example: 例如:
class Employee {
private String id;
private String name;
private String someOtherId;
}
If I need to do a specific operation only to id and someOtherId fields, how can go about it? 如果我只需要对id和someOtherId字段执行特定操作,该怎么办? Can there be custom annotations created to handle this?
是否可以创建自定义注释来处理此问题?
Something like: 就像是:
stringAppend(employee) should do this operation to only the specific fields. stringAppend(employee)应该仅对特定字段执行此操作。 I don't want to check iteratively inside the function, rather I would do it via configuration.
我不想在函数内部进行迭代检查,而是通过配置来进行检查。
The object will be a payload from a HTTPRequest and need to do this manipulation specifically to only certain fields. 该对象将是来自HTTPRequest的有效负载,并且需要专门针对特定字段进行此操作。
For manipulating the specific fields of received object in HTTP request payload, you can use Jackson library in Java. 要处理HTTP请求有效负载中接收到的对象的特定字段,可以使用Java中的Jackson库。 Jackson is a very popular and efficient java based library to serialize or map java objects to JSON and vice versa.
Jackson是一个非常流行且高效的基于Java的库,用于将Java对象序列化或映射到JSON,反之亦然。
In this case from http request body, Employee object will be in serialized formed. 在这种情况下,从http请求正文开始,Employee对象将以序列化形式形成。 To deserialized it to actual Employee object you can use ObjectMapper from Jackson library as follows :
要将其反序列化为实际的Employee对象,可以使用Jackson库中的ObjectMapper,如下所示:
Assume payloadJson
is a string which contains request payload in JSON format. 假设
payloadJson
是一个字符串,其中包含JSON格式的请求有效负载。
ObjectMapper objectMapper = new ObjectMapper();
Employee employee = objectMapper.readValue(payloadJson, Employee.class);
After desrialization you can perform manipulation on fields of Employee object using Getters and Setters method. 反序列化之后,您可以使用Getters和Setters方法对Employee对象的字段执行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.