简体   繁体   English

在Jackson中序列化数组类型和数组

[英]Serializing array types and arrays in Jackson

i have a task serializing a class like RPC message to JSON using Jackson in Java. 我有一个使用Java中的Jackson将诸如RPC消息之类的类序列化为JSON的任务。 I have to say that i´ma complete newbie to Jackson. 我必须说,我是Jackson的新手。 Now what i´m trying to do is to serialize array type into JSON. 现在,我正在尝试将数组类型序列化为JSON。

I have: 我有:

 ObjectMapper mapper = new ObjectMapper(); 

a message is then put into HashMap (simplified) 然后将一条消息放入HashMap(简化)

 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: 对于方法名称“ add”并返回int []类型,结果为:

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

Can anyhone please help me how to achieve "[int]" instead of "[I"? 谁能帮我实现“ [int]”而不是“ [I]”吗?

I assume that 'msg.getReturnType()' returns Class; 我假设'msg.getReturnType()'返回Class; and if so, Jackson will just call toString() on it. 如果是这样,Jackson只会在其上调用toString()。 If so, you would want to instead do conversion yourself, to get actual String value you want. 如果是这样,您可能想自己进行转换,以获得所需的实际String值。

You can also simplify code a bit, since ObjectMapper has 'writeValueAsString()' method: 您还可以稍微简化一下代码,因为ObjectMapper具有'writeValueAsString()'方法:

return mapper.writeValueAsString(wrapper);

which will internally handle creation of StringWriter and JsonGenerator, to achieve what you are doing. 它将在内部处理StringWriter和JsonGenerator的创建,以实现您的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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