将嵌套的json转换为点符号json

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

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

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

 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 map = mapper.readValue(response, new TypeReference<Map>(){}); 

从json字符串到HashMap的转换工作正常,但实际上我的要求是有时在主json中可能有一些嵌套的json,例如在下面的json我有一个额外的address键,这又是一个嵌套的json有citytown细节。

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

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

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

目前我正在使用jackson库,但对任何其他库提供开箱即用的function

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

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

 @SuppressWarnings("unchecked") public static Map flatMap(String parentKey, Map nestedMap) { Map flatMap = new HashMap<>(); String prefixKey = parentKey != null ? parentKey + "." : ""; for (Map.Entry 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)entry.getValue())); } } return flatMap; } 

用法:

 mapper.writeValue(System.out, flatMap(null, nestedMap));