Home > Mobile >  How can I get value of Medicine inside prescription from the response body as given below in Rest As
How can I get value of Medicine inside prescription from the response body as given below in Rest As

Time:10-16

[
    {
        "id": "abd88c05-2919-45f2-b1d0-c99af140bbb0",
        "order_id": "2ddc8302-34e0-437c-8e77-0e0ca80c18ad",
        "user_id": "00000000-0000-0000-0000-000000000001",
        "prescription": "{\"prescription\":[{\"Dosage\":\"2-0-2\",\"Medicine\":\"Hair Ras\",\"composition\":\"\",\"description\":\"Boosts blood circulation to hair follicles\",\"info\":\"Take after meals\",\"is_recommended\":false,\"quantity\":\"2\",\"type\":\"ayurveda\"}]}",
        "created_at": "2022-10-14T13:43:47.039Z",
        "updated_at": "2022-10-14T13:43:47.039Z",
        ...
    }
]

JsonPath js_prescrition = newJsonPath(response_prescription);
Object prescription = js_prescrition.get("prescription");
JsonPath js_prescrition1 = new JsonPath("prescription");
String medicine = js_prescrition.get("Medicine");
System.out.println(medicine);

CodePudding user response:

This code would help you

String data = given()...asString();
String prescription = JsonPath.from(data).getString("[0].prescription").replaceAll("\\\\", "");
List<Map<String, ?>> nested = JsonPath.from(prescription).get("prescription");
String medicine = (String) nested.get(0).get("Medicine");
System.out.println(medicine);
//Hair Ras

CodePudding user response:

Library Josson can do it in a short query statement.

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "["  
    "    {"  
    "        \"id\": \"abd88c05-2919-45f2-b1d0-c99af140bbb0\","  
    "        \"order_id\": \"2ddc8302-34e0-437c-8e77-0e0ca80c18ad\","  
    "        \"user_id\": \"00000000-0000-0000-0000-000000000001\","  
    "        \"prescription\": \"{\\\"prescription\\\":[{\\\"Dosage\\\":\\\"2-0-2\\\",\\\"Medicine\\\":\\\"Hair Ras\\\",\\\"composition\\\":\\\"\\\",\\\"description\\\":\\\"Boosts blood circulation to hair follicles\\\",\\\"info\\\":\\\"Take after meals\\\",\\\"is_recommended\\\":false,\\\"quantity\\\":\\\"2\\\",\\\"type\\\":\\\"ayurveda\\\"}]}\","  
    "        \"created_at\": \"2022-10-14T13:43:47.039Z\","  
    "        \"updated_at\": \"2022-10-14T13:43:47.039Z\""  
    "    }"  
    "]");
    
String medicine = josson.getString("[0].json(prescription).prescription[0].Medicine");
System.out.println(medicine);
  • Related