从java中的json中删除重复的键和值

时间:2018-02-08 15:04:34

标签: java json spring-boot

我将Object(我无法控制)映射到jsonString,映射后我在JSON中获得重复的键值对, 示例

 {
 "id":"123",
 "email":"someEmail@gmail.com",
 "UserName":"someOne",
 "EMAIL":"someEmail@gmail.com"
 }

副本完全相同,只是它是大写字母。 我试图获得jsonInString格式而不重复。像这样:

 {
 "id":"123",
 "email":"someEmail@gmail.com",
 "UserName":"someOne"
 }

我试过了

String jsonInStringWithOutDuplication=mapper.enable(
    JsonParser.Feature.STRICT_DUPLICATE_DETECTION).writeValueAsString(users);

没有运气,有什么建议吗?

2 个答案:

答案 0 :(得分:1)

如果您找不到配置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);

答案 1 :(得分:0)

杰克逊的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);