简体   繁体   中英

Serializing array types and arrays in Jackson

i have a task serializing a class like RPC message to JSON using Jackson in Java. I have to say that i´ma complete newbie to Jackson. Now what i´m trying to do is to serialize array type into JSON.

I have:

 ObjectMapper mapper = new ObjectMapper(); 

a message is then put into HashMap (simplified)

 LinkedHashMap<String,Object> map = new LinkedHashMap<String, Object>();
 if(msg.getSignal())
     map.put("signal",msg.getMethodName());
 else {
     map.put("method", msg.getMethodName());
     map.put("retT", msg.getReturnType()); //returns Class<?> type
 }

 return mapper.writeValueAsString(wrapper);

for method name "add" and return type int[], this results in:

{"method":"add","retT":"[I"}

Can anyhone please help me how to achieve "[int]" instead of "[I"?

I assume that 'msg.getReturnType()' returns Class; and if so, Jackson will just call toString() on it. If so, you would want to instead do conversion yourself, to get actual String value you want.

You can also simplify code a bit, since ObjectMapper has 'writeValueAsString()' method:

return mapper.writeValueAsString(wrapper);

which will internally handle creation of StringWriter and JsonGenerator, to achieve what you are doing.

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