将嵌套json转换为点符号json

时间:2017-07-27 11:29:06

标签: java json jackson2

我有一个服务,从中我得到一个json字符串响应,如下所示

{
  "id": "123",
  "name": "John"
}

我使用HttpClient使用rest调用并将json字符串转换为Map<String, String>,如下所示。

String url= "http://www.mocky.io/v2/5979c2f5110000f4029edc93";
HttpClient client = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-Type", "application/json");
HttpResponse httpresponse = client.execute(httpGet);
String response = EntityUtils.toString(httpresponse.getEntity());

ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(response, new TypeReference<Map<String, String>>(){});

从json字符串到HashMap的转换工作正常,但实际上我的要求是有时在主json中可能有一些嵌套的json,例如在下面的json我有一个额外的{{1} } key,它又是一个具有addresscity详细信息的嵌套json。

town

如果有任何嵌套的json,我需要使json如下所示

{
  "id": "123",
  "name": "John",
  "address": {
    "city": "Chennai",
    "town": "Guindy"
  }
}

目前我正在使用jackson库,但可以打开任何其他库,这些库会让我开箱即用这个功能

任何人都可以通过对此提出一些建议来帮助我。

1 个答案:

答案 0 :(得分:4)

这是一个递归方法,可以将具有任何深度的嵌套Map展平为所需的点表示法。您可以将它传递给杰克逊的ObjectMapper以获得所需的json输出:

@SuppressWarnings("unchecked")
public static Map<String, String> flatMap(String parentKey, Map<String, Object> nestedMap)
{
    Map<String, String> flatMap = new HashMap<>();
    String prefixKey = parentKey != null ? parentKey + "." : "";
    for (Map.Entry<String, Object> entry : nestedMap.entrySet()) {
        if (entry.getValue() instanceof String) {
            flatMap.put(prefixKey + entry.getKey(), (String)entry.getValue());
        }
        if (entry.getValue() instanceof Map) {
            flatMap.putAll(flatMap(prefixKey + entry.getKey(), (Map<String, Object>)entry.getValue()));
        }
    }
    return flatMap;
}

用法:

mapper.writeValue(System.out, flatMap(null, nestedMap));
相关问题