【问题标题】:Loop though Array of Objects and access specific key/value fields遍历对象数组并访问特定的键/值字段
【发布时间】:2020-02-20 23:48:08
【问题描述】:

我有一个看起来像这样的对象:

[
  {
    "title": "Job Title",
    "email": "email@email.com",
    "department": "Department",
    "id": 123456789,
    "name": "First Last"
  }
]

如何循环遍历这个对象并将 email 的值保存在变量中?

这是我的代码:

List<T> results = type.getResults();
String userEmail = "";

for (int i = 0; i < results.size(); i++) {
    if (results.get(i).equals("email")) {
        System.out.println("&&&&&&&&&&& in IF condition &&&&&&&&&&&&&&");
    }
    System.out.println(results.get(i));
}

但我似乎无法让这个循环工作。

【问题讨论】:

  • 这看起来像普通的 JSON。您是否尝试过使用 gson 或 jackson 等解析器?
  • 那不是 JSON 对象吗?
  • 是的,我从 API 调用中获取了这个对象。

标签: java arrays json object key-value


【解决方案1】:

包括 jackson-core 和 jackson-databind 库。 创建如下映射对象:

class User {
    @JsonProperty
    String id;
    @JsonProperty
    String title;
    @JsonProperty
    String email;
    @JsonProperty
    String department;
    @JsonProperty
    String name;
    @Override
    public String toString() {
        return "User [id=" + id + ", email=" + email + "]";
    }

}

将对象映射为数组,如下所示:

ObjectMapper objectMapper=new ObjectMapper();
        User[] users=objectMapper.readValue("[ { \"title\": \"Job Title\", \"email\": \"email@email.com\", \"department\": \"Department\", \"id\": 123456789, \"name\": \"First Last\" } ]", User[].class);
        System.out.println(users[0]);

【讨论】:

    【解决方案2】:

    您可以将此 json 字符串解析为 List.class,然后对内部对象使用 typecasting

    String json = "[{" +
            "\"title\": \"Job Title\"," +
            "\"email\": \"email@email.com\"," +
            "\"department\": \"Department\"," +
            "\"id\": 123456789," +
            "\"name\": \"First Last\"" +
            "}]";
    
    List list = new ObjectMapper().readValue(json, List.class);
    
    Map<String, Object> map = (Map<String, Object>) list.get(0);
    
    Object email = map.get("email");
    Object id = map.get("id");
    
    System.out.println("email: " + email + ", id: " + id);
    // email: email@email.com, id: 123456789
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 2017-06-07
      • 2020-07-21
      • 2021-10-14
      相关资源
      最近更新 更多