How get just one value from json as string

Viewed 47

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?

2 Answers

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!

Related