【问题标题】:Json map to java object from inner - nested json propertyJson 从内部嵌套的 json 属性映射到 java 对象
【发布时间】:2017-12-06 13:18:47
【问题描述】:

假设我有如下 JSON。

{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 1,
        "hits": [
            {
                "_index": "users",
                "_type": "students",
                "_id": "AWAEqh945A0BWjveqnd0",
                "_score": 1,
                "_source": {
                    "college": {
                        "sport": {
                            "name": "cricket",
                            "category": "batsman"
                        }
                    }
                }
            }
        ]
    }
}

我想将数据映射到从 _source 字段开始的 College 对象。

有没有办法告诉 Jackson 或 Gson 应该从哪里开始映射? 在这个例子中来自_source

我们从 ES 服务器得到的响应。 托管在 AWS 上的 ES 服务器。 所以我们假设通过 ES Java API RestClient 进行通信。 可以通过 ES Java API QueryBuilder 查询。 推荐什么。 ?

【问题讨论】:

  • 您是从 elasticsearch 获取这些数据吗?
  • 感谢您的回复。我正在使用 ES java api。休息客户端。如何从 RestClient 获取 SearchResponse。由于 ES 托管在 AWS 上,我们必须通过 REST 进行通信,是否可以通过 ES QueryBuilder 进行查询 -
  • 没有得到问题
  • 请显示您的代码的相关部分。

标签: java json elasticsearch jackson gson


【解决方案1】:

您可以使用 Gson 执行以下操作:

    JSONObject object = new JSONObject(s); // s is you String Json
    JSONObject hits1 = object.getJSONObject("hits");
    JSONArray hits = hits1.getJSONArray("hits");
    for (Object jsonObj : hits) {
        JSONObject json = (JSONObject) jsonObj;
        JSONObject source = json.getJSONObject("_source");
        College college = new Gson().fromJson(source.getJSONObject("college").toString(), College.class);
    }

你还需要这两个 Pojo:

public class College {

    private Sport sport;

    public College() {
    }

    public Sport getSport() {
        return sport;
    }

    public void setSport(Sport sport) {
        this.sport = sport;
    }
}

public class Sport {

    private String name;
    private String category;

    public Sport() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}

【讨论】:

    【解决方案2】:

    我使用了下面提到的方式。

     ObjectMapper objectMapper = new ObjectMapper();
     JsonNode jsonNode = objectMapper.readTree(resultJson);
     String sourceString = jsonNode.at("/hits/hits/0/_source").toString();
    
     College college = objectMapper.readValue(sourceString, College.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 2021-07-06
      • 2015-07-30
      • 1970-01-01
      • 2020-03-19
      相关资源
      最近更新 更多