简体   繁体   中英

Java Jackson JSON parse into Map<String, String>

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.

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>>() { });

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

I think you are looking for keyAs . Please have a look at Jackson Documentation for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM