在java中从json中删除重复的键和值
我正在将在java中从json中删除重复的键和值,java,json,spring-boot,Java,Json,Spring Boot,我正在将对象(我没有控制权)映射到jsonString,映射之后,我在JSON中获得了重复的键值对, 范例 除了大写字母外,副本完全相同。 我正在尝试获得一个不重复的jsonInString格式。大概是这样的: { "id":"123", "email":"someEmail@gmail.com", "UserName":"someOne" } 我试过了 String jsonInStringWithOutDuplication=mapper.enable( JsonPars
对象
(我没有控制权)映射到jsonString
,映射之后,我在JSON中获得了重复的键值对,
范例
除了大写字母外,副本完全相同。
我正在尝试获得一个不重复的jsonInString
格式。大概是这样的:
{
"id":"123",
"email":"someEmail@gmail.com",
"UserName":"someOne"
}
我试过了
String jsonInStringWithOutDuplication=mapper.enable(
JsonParser.Feature.STRICT_DUPLICATE_DETECTION).writeValueAsString(users);
如果运气不好,有什么建议吗?Jackson的ObjectMapper具有将相同的键放入数组的功能。这不是对你有帮助吗
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new GuavaModule());
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Multimap resultAsMultimap = mapper.readValue(json, Multimap.class);
System.out.println(resultAsMultimap);
如果找不到配置
ObjectMapper
以过滤重复属性的方法,可以将有问题的对象序列化为JSON,然后将JSON序列化为Map
对象,合并重复属性并再次序列化为JSON:
Map<String, String> objectWithDuplicates = new HashMap<>();
map.put("name", "MyName");
map.put("email", "em@ail");
map.put("EMAIL", "em@ail");
ObjectMapper mapper = new ObjectMapper();
String jsonWithDuplicates = mapper.writeValueAsString(objectWithDuplicates);
Map<String, Object> attributesWithDuplicates = mapper
.readValue(jsonWithDuplicates, Map.class);
Map<String, Object> withoutDuplicates = new HashMap<>();
attributesWithDuplicates.forEach((key, value) -> {
if (! withoutDuplicates.containsKey(key.toLowerCase())) {
withoutDuplicates.put(key.toLowerCase(), value);
}
});
String json = mapper.writeValueAsString(withoutDuplicates);
MapObjectWithDuplicates=newHashMap();
地图。放置(“名称”、“我的名称”);
map.put(“电子邮件”)em@ail");
map.put(“电子邮件”)em@ail");
ObjectMapper mapper=新的ObjectMapper();
字符串jsonWithDuplicates=mapper.writeValueAsString(objectWithDuplicates);
映射属性WithDuplicates=映射器
.readValue(jsonWithDuplicates,Map.class);
Map withoutDuplicates=新建HashMap();
attributesWithDuplicates.forEach((键,值)->{
如果(!withoutDuplicates.containsKey(key.toLowerCase())){
withoutDuplicates.put(key.toLowerCase(),value);
}
});
字符串json=mapper.writeValueAsString(无重复项);
它们不是重复的,您需要首先安排您的hashmappThank you@JánHalaša,这很有帮助。
Map<String, String> objectWithDuplicates = new HashMap<>();
map.put("name", "MyName");
map.put("email", "em@ail");
map.put("EMAIL", "em@ail");
ObjectMapper mapper = new ObjectMapper();
String jsonWithDuplicates = mapper.writeValueAsString(objectWithDuplicates);
Map<String, Object> attributesWithDuplicates = mapper
.readValue(jsonWithDuplicates, Map.class);
Map<String, Object> withoutDuplicates = new HashMap<>();
attributesWithDuplicates.forEach((key, value) -> {
if (! withoutDuplicates.containsKey(key.toLowerCase())) {
withoutDuplicates.put(key.toLowerCase(), value);
}
});
String json = mapper.writeValueAsString(withoutDuplicates);