从大型响应对象中检索几个字段

huangapple go评论75阅读模式
英文:

Retrieving a few fields from large response object

问题

我正在调用Google Directory API,并且只需要返回的一些字段。我对Java/Spring相对不熟悉,所以我正在尝试找出最佳的方法。我目前的请求是这样的:

restTemplate.exchange(url, HttpMethod.GET, req, Object, userKey);

我目前将其设置为Object,但不确定是否正确。当我只需要一些字段时,我不想映射出它返回的非常庞大的对象。是否有一种方法可以访问字段phone, organizations, locations

res.getClass().getField("phones")对我不起作用。

为了说明对象的形状,我们可以考虑以下示例:

{ 
    "phones": [{"type": "String", "number": "String"}], 
    "organizations": [{"title": "String"}], 
    "locations": [{"buildingId": "String"}]  
}
英文:

I am making a call to Google Directory API and only need a few fields it is returning. I am fairly new to Java/Spring so I am trying to figure out what is the best way to go about this. I am making my request like this:

restTemplate.exchange(url, HttpMethod.GET, req, Object, userKey);

I currently have it as an Object, but not sure if this is correct. I do not want to map out the very large object it returns when I only need a few fields. Is there a way to access the fields, phone, organizations, locations ?

res.getClass().getField("phones") did not work for me.

For purposes we can consider the shape of the object:

{ 
    phones: [type: String, number: String], 
    organizations: [title: String], 
    locations: [buildingId: String]  
}

答案1

得分: 0

你可以将响应的 JSON 解析为 JsonNode。

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree("【在这里填入你的 JSON】");

然后只获取你需要的字段。例如:

jsonNode.get("request").get("phones").get("type").asText()

或者只获取 phones 对象。

英文:

You can parse your response JSON as JsonNode.

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree("[your JSON here]");
After that get only fields, which you need. For example:

jsonNode.get("request").get("phones").get("type").asText()

or just a phones object

答案2

得分: -1

你应该能够执行类似以下的操作。在这里,“User”是 com.google.api.services.admin.directory.model.User

List<User> users = result.getUsers();
if (users == null || users.size() == 0) {
    System.out.println("未找到用户。");
} else {
    System.out.println("用户:");
    for (User user : users) {
        System.out.println(user.getName().getFullName());
    }
}
英文:

You should be able to do something like below. Here "User" is com.google.api.services.admin.directory.model.User

    List&lt;User&gt; users = result.getUsers();
    if (users == null || users.size() == 0) {
        System.out.println(&quot;No users found.&quot;);
    } else {
        System.out.println(&quot;Users:&quot;);
        for (User user : users) {
            System.out.println(user.getName().getFullName());
        }
    }

huangapple
  • 本文由 发表于 2020年9月26日 03:02:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64070014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定