问题描述
我有一个 api,我正在接收一个 json 格式的 Java pojo 请求:
I have an api for which I am receiving a Java pojo request in json format:
{
"migrationId" : "32n2342342j";
"someDynamicField" : {"A" : "",
"B" : ""}
}
这个 someDynamicField
可以有不同的属性名称,我需要从中提取数据.
我不能为这个模型创建一个类,因为该字段是动态的.
但可以肯定的是 someDynamicField
将是字符串类型,但名称会有所不同.
有一点是肯定的,someDynamicField
可以是有限集合中的字符串之一,例如:[move", source"....] 并且这个集合会增长在未来.
例如:
This someDynamicField
can have different property name for which I need to extra the data from.
I cannot have a class for this model since that field is dynamic.
But for sure that someDynamicField
will be of string type but name will be different.
One thing is for sure that someDynamicField
can be one of the string from the finite set for eg: ["move", "source"....] and this set will grow in future.
For example :
{
"migrationId" : "32n2342342j";
"move" : {"sourHost" : "",
"targetHost" : ""}
}
有时可能
{
"migrationId" : "32n2342342j";
"delete" : {"sourHost" : "",
"targetHost" : ""}
}
从请求中提取此信息的最佳方法是什么?
我试着看看这个:如何映射动态 JSON在 JAX-RS 中
在这里,他们显式使用变量名称,而在我的情况下,该字段是动态的?
What would be the best way to extract this information from the request?
I tried to look at this one : How to map dynamic JSON in JAX-RS
Here they use the vairable name explicitly and in my case the field is dynamic?
推荐答案
我会使用 String 而不是 Object 并用 Jackson 解析它.这不是完整的代码,而是类似于:
I would take a String instead of an Object and parse it with Jackson. This isn't the complete code but something like:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON})
@Path("/blah")
public Response myMethod(String inputObject) {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(inputObject);
String migrationId = jsonNode.get("migrationId");
if( jsonNode.has("move") ) {
handleMoveNode(jsonNode.get("move"));
}
else if( jsonNode.has("delete") ) {
handleDeleteNode(jsonNode.get("delete"));
}
// handle the other node types
return Response.ok().build();
}
重点是在您的 JAX-RS 方法中获取一个字符串并自己解析它.
The point is to take a String in your JAX-RS method and parse it yourself.
这篇关于如何从 JAX-WS (JAX_RS) 中的 json 请求中获取动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!