How to access a specific field of a JSON object using JAVA

Asked

Viewed 271 times

1

I’m using Java to get information from Twitter and the REST client Elasticsearch.

As a test I did a PUT of info in JSON and then used the performRequest to obtain a specific element.

//create a json to PUT at the ES
    Map<String, String> params2 = Collections.emptyMap();
    String jsonString = "{" +
                "\"user\":\"Luisinho\"," +
                "\"postDate\":\"1988\"," +
                "\"message\":\"esta a começar a andar\"" +
            "}";
    HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
    Response response4 = restClient.performRequest("PUT", "/posts/doc/2", params, entity);


    //Search the document using Query Params

    Map<String, String> paramMap = new HashMap<String, String>();
    paramMap.put("q", "user:Luisinho");
    paramMap.put("pretty", "true");

    Response response5 = restClient.performRequest("GET", "/posts/_search",
                                                               paramMap);

    System.out.println(EntityUtils.toString(response5.getEntity()));
    System.out.println("Host -" + response5.getHost() );

And I got the desired element this way:

   {
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "posts",
        "_type" : "doc",
        "_id" : "2",
        "_score" : 0.2876821,
        "_source" : {
          "user" : "Luisinho",
          "postDate" : "1988",
          "message" : "esta a começar a andar"
        }
      }
    ]
  }
}

Host -http://localhost:9200

1- It is possible to obtain this information already as a JSON object?

2- Since I don’t know how to do the first one, I converted that information to a JSON object, but how do I get the value of the key "message" which is what interests me?

I tried something like:

String nova=EntityUtils.toString(response5.getEntity());
JSONObject jsonObj = new JSONObject(nova);
String message = jsonObj.getJSONObject("hits").getString("message");
        System.out.println("JSON  "+message);

But I can’t get the desired value.

1 answer

1

To make it easier to get the value "message". Create a pojo with all fields returned from json. Once this is done, use the GSON library to convert your json to the pojo created. That way you can get the value without problems!

Something like that:

Gson gson = new Gson();
String jsonInString = "   {
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "posts",
        "_type" : "doc",
        "_id" : "2",
        "_score" : 0.2876821,
        "_source" : {
          "user" : "Luisinho",
          "postDate" : "1988",
          "message" : "esta a começar a andar"
        }
      }
    ]
  }
}";
PojoCriado pojoCriado= gson.fromJson(jsonInString, PojoCriado.class);
pojoCriado.getHits.getMessage();
  • POJO is something new for me. From what I’ve seen it works as a kind of Model of an object? Do I have to create this can with all 18/19 fields returned? And when doing gson.fromJson(jsonInString, Pojocriado.class) what does it do? does the sets of all fields? Sorry ignorance and thank you

  • Perfect friend! That’s just it. When doing gson.fromJson(jsonInString, Pojocriado.class) it will set the values of your pojo according to the file passed as parameter .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.