Home > Software design >  How get just one value from json as string
How get just one value from json as string

Time:02-03

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?

CodePudding user response:

Try JSONPath

String json = "...";

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

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

CodePudding user response:

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!

  •  Tags:  
  • Related