0

Suppose I have JSON as follow.

{
    "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"
                        }
                    }
                }
            }
        ]
    }
}

I want to map data to College object which start from _source field.

Is there way to say to Jackson or Gson to from where mapping should start ? in this example from _source

The Response we get from ES server. ES server hosted on AWS. So we suppose to communicate through ES Java API RestClient. Is it ok Query through ES Java API QueryBuilder. What is Recommended. ?

Chamly Idunil
  • 1,848
  • 1
  • 18
  • 33

2 Answers2

1

I used below mention way.

 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);
Chamly Idunil
  • 1,848
  • 1
  • 18
  • 33
0

You can do the following using 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);
    }

You also need these two Pojos:

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;
    }
}
Gal Shaboodi
  • 744
  • 1
  • 7
  • 25