将嵌套的json转换为点表示法json [英] Converting Nested json into dot notation json
问题描述
我有一个服务,可以从其中获得如下所示的json字符串响应
I have a service from where I get a json string response like as shown below
{
"id": "123",
"name": "John"
}
我使用HttpClient消耗剩余的调用,并将json字符串转换为Map<String, String>
,如下所示.
I consume the rest call using HttpClient and converts the json string to Map<String, String>
like as shown below.
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中,我有一个附加的address
键,再次是具有city
和town
详细信息的嵌套json.
The conversion from json string to HashMap
is working fine, but actually my requirement was sometimes there can be some nested json within the main json, for example in the below json I am having an additional address
key which is again a nested json having city
and town
details.
{
"id": "123",
"name": "John",
"address": {
"city": "Chennai",
"town": "Guindy"
}
}
如果有嵌套的json,则需要使json如下所示
If any nested json comes I need the make the json like as shown below
{
"id": "123",
"name": "John",
"address.city": "Chennai",
"address.town": "Guindy"
}
目前,我正在使用杰克逊图书馆,但可以使用其他任何可以立即使用此功能的图书馆
Currently I am using jackson library, but open to any other library which will give me this feature out of box
有人可以为此提出一些建议吗?
Can anyone help me by giving some suggestion on this.
推荐答案
此处是一种递归方法,该方法可以将具有任意深度的嵌套Map展平为所需的点表示法.您可以将其传递给Jackson的ObjectMapper
以获取所需的json输出:
Here is a recursive method that will flatten a nested Map with any depth to the desired dot notation. You can pass it to Jackson's ObjectMapper
to get the desired json output:
@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));
这篇关于将嵌套的json转换为点表示法json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!