You can use gson library. If your input is a JSON string, you first need to parse it using a JsonParser
object which returns us a JsonElement
which is converted into JsonArray as the input Json is an array. You then extract the first object from it using get(0)
and then convert it into a JsonObject
, extract preferences
element as JsonArray and follow similar procedure to get Entity
.
String jsonString = "[" +
" {" +
" \"_id\": john," +
" \"preferences\": [" +
" {" +
" \"Entity\": [" +
" IBM," +
" Pfizer" +
" ]" +
" }," +
" {" +
" \"Topic\": Pharma" +
" }" +
" ]" +
" }" +
"]";
JsonArray jsonArray = new JsonParser().parse(jsonString).getAsJsonArray();
JsonArray preferences = jsonArray.get(0).getAsJsonObject().get("preferences").getAsJsonArray();
JsonArray entity = preferences.get(0).getAsJsonObject().get("Entity").getAsJsonArray();