将JSON字符串转换为“Object.class” [英] Convert JSON string to "Object.class"
问题描述
我目前正在尝试使用Jackson将对象转换为JSON字符串,这很容易通过
I am currently trying to use Jackson to turn an object into a JSON string this was easily done by
public byte[] toJSON(Object obj) throws IOException {
ObjectMapper map = new ObjectMapper();
return map.writeValueAsString(obj).getBytes();
}
我遇到麻烦的地方是我要拿字节数组和把它们变成一个对象。目前我有:
Where i run into trouble is when i was to take the array of bytes and turn them into an Object. Currently i have:
public Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
ObjectMapper map = new ObjectMapper();
return (Object)map.readValue(bytes, Object.class);
}
我成功将对象转换为JSON字符串,但是从toObject返回了Object方法总是一个LinkedHashMap而不是最初变成JSON字符串的对象。
I successfully convert an object to a JSON string but the Object returned from the toObject method is always a LinkedHashMap instead of the object that was initially turned into the JSON string.
很抱歉,如果我在沟通我的问题上做得不好但是生病了,试着总结一下只是。我希望我的代码能够执行以下操作:
Sorry if i did a poor job communicating my problem but ill try to sum it up simply. I want my code to be able to do the following:
MyClass someObject = new MyClass();
String json = toJSON(someObject);
Object tempObject = toObject(json);
MyClass sameObject = (MyClass) tempObject;
此代码目前抛出以下内容:
this code currently throws the following:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.MyClass
任何有关此事的帮助都将不胜感激!
Any help on the matter would be appreciated!
推荐答案
您正在申请对象
,因此杰克逊创建了一个对象
它知道它可以创建: Map
。 JSON数组将成为 List
等等。
You are requesting an Object
, so Jackson creates one Object
it knows it can create: a Map
. JSON array would become a List
and so on.
如果你想要 MyClass
,您必须明确地请求它,或者,如果您想要通用序列化/反序列化,请包含类型标识符,如@csd所示。
If you want MyClass
, you must request it explicitly, or, if you want a general-purpose serialization/deserialization, for inclusion of type identifier, as suggested by @csd.
这篇关于将JSON字符串转换为“Object.class”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!