Tomy
Tomy

Reputation: 23

How get just one value from json as string

I have following json as string:

{
   "field1":"value1",
   "field2":"value2",
   "field3":{
      "field31":"value31",
      "field32":"value32"
   },
   "field4":{
      "field41":"value41"
   }
}

What is the best and the most modern way to get from this json just value from field41, so I would return "value41". I know that I can use JSONObject but I'm wondering weather we have any other better option?

Upvotes: 1

Views: 62

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191973

Try JSONPath

String json = "...";

String field41 = JsonPath.read(json, "$.field4.field41");

You can test it here - https://jsonpath.herokuapp.com/

Upvotes: 1

Uriel Frankel
Uriel Frankel

Reputation: 14622

If you want to generate a real object out of it you can use Gson. You need to describe the class first. There are online json to Java objects converters out there. And then you can just call:

YourObject obj =  new Gson().fromJson(json,YourObject.class);
System.out.println(obj.getField4().getField41());

And there you have it!

Upvotes: 1

Related Questions