3

I am mapping Object (i don't have control over) to jsonString, after mapping I get duplicate key-value pairs in the JSON, example

 {
 "id":"123",
 "email":"[email protected]",
 "UserName":"someOne",
 "EMAIL":"[email protected]"
 }

the duplicate is exactly the same except that it is in uppercase letters. I am trying to get a jsonInString format without the duplication. Something like this:

 {
 "id":"123",
 "email":"[email protected]",
 "UserName":"someOne"
 }

I have tried

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

with no luck, any suggestions?

1
  • they are not duplicate, you need first to arrange your hashmap Commented Feb 9, 2018 at 12:30

2 Answers 2

1

If you don't find a way to configure the ObjectMapper to filter out duplicate attributes, you can serialize the problematic object to JSON, then serialize the JSON to a Map object, merge duplicate attributes and serialize it to JSON again:

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @JánHalaša that helped.
0

Jackson's ObjectMapper has a feature that puts the same keys into an array. Isn't it something that could help you?

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.