1

i have a task serializing a class like RPC message to JSON using Jackson in Java. I have to say that i´m a 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"?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm passing a Class as a return type, but i have been hoping that Jackson can handle the conversion. But can you navigate me how do i do that on my own? Do i have to create wrapper around Class with custom toString, or is there an another way?
Jackson can, as you can see; it just uses standard mechanism. And what you want is something different. To customize, you can either define custom serializer (and possible deserializer); or just convert Class<?> to String yourself and avoid any Jackson work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.