0

I need to convert a map to JSON string, I am using a third-party library and one of the classes in it has a field of type Map<String, Object> I need to convert that map to JSON string and send it to its destination. All works ok until I put a string into that map as a value i.e. if that Object in the map is a String then I end up having four double quotes (""value"") in the final JSON string I get from jackson's OBJECT_MAPPER.writeValueAsString(str) method.

e.g. the following this map:

map.put("key", "value") of type Map<String, Object> will result in {"key" : ""value""} which obviously is not a JSON string, any idea how to resolve this without writing a custom method to check types and solve the issue?

Toseef Zafar
  • 1,601
  • 4
  • 28
  • 46

1 Answers1

0

Try to use com.google.gson.Gson

   public void convertMapToJson() {
        SortedMap<String, String> elements = new TreeMap();
        elements.put("Key1", "Value1");
        elements.put("Key2", "Value2");
        elements.put("Key3", "Value3");

        Gson gson = new Gson();
        Type gsonType = new TypeToken<HashMap>(){}.getType();
        String gsonString = gson.toJson(elements,gsonType);
        System.out.println(gsonString);
    }
Azzabi Haythem
  • 2,318
  • 7
  • 26
  • 32