本文介绍了在RESTEasy Client中提取JSON响应的特定节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RESTEasy客户端从API检索JSON字符串。 JSON有效负载看起来像这样:

I'm retrieving a JSON string from an API using a RESTEasy client. The JSON payload looks something like this:

{
  "foo1" : "",
  "foo2" : "",
  "_bar" : {
    "items" : [
      { "id" : 1 , "name" : "foo", "foo" : "bar" },
      { "id" : 2 , "name" : "foo", "foo" : "bar" },
      { "id" : 3 , "name" : "foo", "foo" : "bar" },
      { "id" : 4 , "name" : "foo", "foo" : "bar" }
    ]
  }
}

现在我只想提取 items 对象映射的节点。截取JSON响应主体并将其修改为具有 items 作为根节点的最佳方法是什么?

Now I'd like to extract only the items node for object mapping. What is the best way to intercept the JSON response body and modify it to have items as root node?

我正在使用。

REST客户端代码:

The REST client code:

ResteasyWebTarget target = client.target("https://"+server);
target.request(MediaType.APPLICATION_JSON);
client.register(new ClientAuthHeaderRequestFilter(getAccessToken()));
MyProxyAPI api = target.proxy(MyProxyAPI.class);
MyDevice[] result = api.getMyDevice();

RESTEasy代理接口:

RESTEasy proxy interface:

public interface MyProxyAPI {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/device")
    public MyDevice[] getMyDevices();

    ...
}


推荐答案

你可以创建一个并使用Jackson来操纵你的JSON:

You could create a ReaderInterceptor and use Jackson to manipulate your JSON:

public class CustomReaderInterceptor implements ReaderInterceptor {

    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context)
                      throws IOException, WebApplicationException {

        JsonNode tree = mapper.readTree(context.getInputStream());
        JsonNode items = tree.get("_bar").get("items");
        context.setInputStream(new ByteArrayInputStream(mapper.writeValueAsBytes(items)));
        return context.proceed();
    }
}

然后注册已创建上面的:

Then register the ReaderInterceptor created above in your Client:

Client client = ClientBuilder.newClient();
client.register(CustomReaderInterceptor.class);

这篇关于在RESTEasy Client中提取JSON响应的特定节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 08:59