Java Jackson JSON parses into Map <String, String>

I need to pass the parsed JSON map to some method that has the following signature:

QUEUE.sendMsg(Map<String, String> data); 

Unfortunately, I have no control over the above method, and Jackson gives me the parsed JSON in Map<String, Object> .

I need Map<String, String> where

  • for primitive JSON types instead of Integer, Long, Boolean, I want to convert the value toString ().
  • for complex JSON types such as List / Map, save the result in native JSON format to String.

For example, if the input is JSON

 { "name" = "John", "marked" = false, "age" = 30, "tags" = [ "work", "personal" ], "meta" = { "k1" : "v1", "k2" : "v2" }, } 

I want a Map<String, String> that has

 map.get("name") returns "John", map.get("marked") returns "false", map.get("age") returns "30", map.get("tags") returns "[ \"work\", \"personal\" ]", map.get("meta") returns "{ \"k1\" : \"v1\", \"k2\" : \"v2\" }" 

Is there a way to achieve this?

Unfortunately, I'm almost new to Java and don't know about Jackson (I have to use Jackson for this solution).

Thanks.

+2
source share
3 answers

Yes, implicit conversions should work as long as you make sure that you pass information of type FULL. So something like:

 Map<String,String> map = mapper.readValue(jsonSource, new TypeReference<Map<String,String>>() { }); 
+1
source

Something like this should work ...

 final Map<String, Object> input = ...; final Map<String, String> output = new Map<>(input.size()); final StringWriter writer = new StringWriter(); final StringBuffer buf = writer.getBuffer(); for (final Map.Entry<String, Object> entry : input.entrySet()) { try (final JsonGenerator gen = JsonFactory.createJsonGenerator(writer)) { gen.writeObject(entry.getValue()); } output.put(entry.getKey(), buf.toString()); buf.setLength(0); } 
0
source

I think you are looking for keyAs . Please see Jackson Documentation for more details.

0
source

All Articles