0

I wanted to get element value at specific position using keys. For example :: I want to get value for

  1. personalDetails.name
  2. products[1].productName
  3. products[1].productPrice

when i try to fetch the value from jsonobject using

JsonElement el = JsonParser.parseString(json);

JsonObject object=el.getAsJsonObject();

object.get("personalDetails.name");       // I get value as null

object.get("products[1].productName");    // I get value as null

I did try different approaches like /products/1/productName , /personalDetails/name, but it dosent work.

My json looks like

{
    "accountNumber": "9876543215345353453453453454",
    "amount": "$49",
    "personalDetails": {
        "name": "ankit ostwal"
    },
    "products": [{
        "productName": "watch",
        "productPrice": "$21"
    }, {
        "productName": "belt",
        "productPrice": "$4"
    }, {
        "productName": "belt",
        "productPrice": "$4"
    }]
}

Let me know if anyone can help. Thanks.

Ankit Ostwal
  • 1,033
  • 3
  • 14
  • 32
  • This does not work because `JsonObject.get` only obtains the member with that specific name, for example `"products"` and not complete paths you are using. Maybe you are looking for using JSONPath? – Marcono1234 May 28 '23 at 13:27
  • Does this answer your question? [Jsonpath with Jackson or Gson](https://stackoverflow.com/questions/34111276/jsonpath-with-jackson-or-gson) – Marcono1234 May 28 '23 at 13:27
  • Hi @Marcono1234 , I specifically wanted to do it using GSON, I was able to achieve it using Jackson using path like /products/1/productPrice? But was just trying to figure if i cna do it using GSON, so i dont have to use multiple libraries as my existing implementation is using GSON everywhere. – Ankit Ostwal May 29 '23 at 08:50
  • No, Gson does not support this natively. You would have to use a separate library which adds JSONPath support for Gson, see the question I linked above; more specifically see https://github.com/json-path/JsonPath. See also [this Gson issue](https://github.com/google/gson/issues/1443) which requests JSON Pointer support. – Marcono1234 May 29 '23 at 15:16
  • Ok, lemme check... – Ankit Ostwal May 30 '23 at 09:21

0 Answers0