Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Jackson JSON parse into Map<String, String>

Tags:

java

json

jackson

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

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

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

I need a Map<String, String> where

  1. for the primitive JSON types, instead of Integer, Long, Boolean, I want its toString() converted value.
  2. for the complicated JSON types such as List/Map, store the result in native JSON format in String.

For example, if the JSON input is

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

I want a Map<String, String> which 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 any way to achieve this goal?

Unfortunately, I'm almost new to Java, and has no prior knowledge of Jackson (I have to use Jackson for this solution).

Thank you.

like image 615
cinsk Avatar asked Apr 26 '26 22:04

cinsk


1 Answers

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

Map<String,String> map = mapper.readValue(jsonSource, new TypeReference<Map<String,String>>() { });
like image 116
StaxMan Avatar answered Apr 28 '26 12:04

StaxMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!