Home > Back-end >  how to take json data in java map or array
how to take json data in java map or array

Time:09-12

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?

CodePudding user response:

First you need to make your data is a valid json format,then you can use enter image description here

CodePudding user response:

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}

  • Related