0

I have 2 classes created, Class1 and Class2 like this:

Class1{
   String a;
   String b;
   String c;
}

Class2{
   String d;
   String e;
   String f;
}

The Map is created in this manner:

Map<Class1, Class2> map1 = new LinkedHashMap<Class1, Class2>();

map1.put(new Class1("Apple", "Ball", "Cat"),
         new Class2("Dog","Elephant","Frog"));

I am converting this Map like this:

public static String convertMapToJson(Map input) {
    if (input == null || input.size() == 0)
        return null;
    ObjectMapper mapper = new ObjectMapper();
    String json = "";        try {
        json = mapper.writeValueAsString(input);
    } catch (Exception e) {
        logger.finer(e.getMessage());
    }
    return json;
}

I am expecting the Json string to be:

"a":"Apple","b":"Ball","c":"Cat"{
  "d":"Dog",
  "e":"Elephant",
  "f":"Frog"
}

But i see the output as with the Object Name, i am not sure why the key is not converted to Json

"Object Name@12353"{
  "d":"Dog",
  "e":"Elephant",
  "f":"Frog"
}
Michael
  • 34,340
  • 9
  • 58
  • 100
  • 1
    Linked duplicate is for Date but same principle applies. Map keys are serialized with `toString` by default, which your class does not have. – Michael Jul 19 '19 at 10:28
  • `"a":"Apple","b":"Ball","c":"Cat"{"d":"Dog","e":"Elephant","f":"Frog"}` - is invalid `JSON`. `JSON Object` can not be used as a property name. – Michał Ziober Jul 19 '19 at 12:28

0 Answers0