0

I have the following data as json and I want to take it in java

"endPoints": {
                "northAmerica": "https://ad-api.com",
                "europe": "https://ad-api-eu.com",
                "farEast": "https://ad-api-fe.com"
            }

I have tried the below code but not working.

Map<String, Object> endPoints = objectMapper.readValue(JsonParser
                    .parseString(additionalInfo().get("endPoints").toString())
                    .getAsJsonObject(), new TypeReference<Map<String, Object>>() {
                    });

anyone can help me how to do it?

Kunaal
  • 21
  • 3

2 Answers2

0

First you need to make your data is a valid json format,then you can use ObjectMapper to do it

public static void testJsonConvert() throws JsonProcessingException {
    String data = "{\n" +
            "    \"endPoints\":{\n" +
            "        \"northAmerica\":\"https://ad-api.com\",\n" +
            "        \"europe\":\"https://ad-api-eu.com\",\n" +
            "        \"farEast\":\"https://ad-api-fe.com\"\n" +
            "    }\n" +
            "}";
    Map<String, Object> map = new ObjectMapper().readValue(data, HashMap.class);
    System.out.println(map);
}

Test result: enter image description here

flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • I'm getting "{northAmerica=https://ad-api.com, europe=https://ad-api-eu.com, farEast=https://ad-api-eu.com}" I've used "String endpoints = additionalInfo().get("endPoints").toString();" The String data you told me, is there any way to do it or do I have to do It manually? – Kunaal Sep 12 '22 at 06:51
  • @Kunaal you need to do it manually – flyingfox Sep 12 '22 at 07:34
0

Any JSON string can be mapped to HashMap data structure as Key and Value pair.

There is an answer already in the thread.

But If you want a map of endpoints, like North America & Europe, you need to go a level deeper.

ObjectMapper from Jackson Core library will help.

First, get a HashMap of the data, then again get the endpoint from the HashMap.

String data = "{\n" +
    "    \"endPoints\":{\n" +
    "        \"northAmerica\":\"https://ad-api.com\",\n" +
    "        \"europe\":\"https://ad-api-eu.com\",\n" +
    "        \"farEast\":\"https://ad-api-fe.com\"\n" +
    "    }\n" +
    "}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(data, HashMap.class);
Map<String, Object> endPointMap = (Map<String, Object>) map.get("endPoints");
System.out.println(endPointMap);

result:

{northAmerica=https://ad-api.com, europe=https://ad-api-eu.com, farEast=https://ad-api-fe.com}

anantha ramu
  • 171
  • 4