Search code examples
javajsonspringspring-bootdto

How to parse only 1 variable from JSON HTTP response Spring Boot


Hi I would like to parse only 1 value from GET response in the most optimal way using Java (+Spring Boot).

{
    "table": "A",
    "currency": "usd",
    "code": "USD",
    "rates": [
        {
            "no": "073/A/NBP/2021",
            "effectiveDate": "2021-04-16",
            "mid": 3.7978
        }
    ]
}

Im looking for way to parse "mid" value without creating DTO for this response. In the worst case I will do just a substring.


Solution

  • Try this.

    String input = "{\r\n"
        + "    \"table\": \"A\",\r\n"
        + "    \"currency\": \"usd\",\r\n"
        + "    \"code\": \"USD\",\r\n"
        + "    \"rates\": [\r\n"
        + "        {\r\n"
        + "            \"no\": \"073/A/NBP/2021\",\r\n"
        + "            \"effectiveDate\": \"2021-04-16\",\r\n"
        + "            \"mid\": 3.7978\r\n"
        + "        }\r\n"
        + "    ]\r\n"
        + "}";
    String midValue = input.replaceFirst("(?s).*\"mid\"\\s*:\\s*([-.\\d]+).*", "$1");
    System.out.println(midValue);
    

    output:

    3.7978