大家好,谢谢。我在Java中使用Reflection来获取所有类字段,并用反序列化的JSON消息中的值填充它们。但是我总是会收到类似的错误
Exception in thread "Thread-2" java.lang.IllegalArgumentException:
Can not set short field Message.Error to java.lang.String
这是发生这种情况的片段:
public static Message Decode(String request) {
JSONObject obj = new JSONObject(request);
Message msg = new Message();
for (Field fld :msg.getClass().getDeclaredFields())
if (obj.has(fld.getName())) {
try {
msg.getClass().getField(fld.getName()).set(msg, obj.get(fld.getName()));
} catch (IllegalAccessException e) {
return null;
} catch (NoSuchFieldException e) {
return null;
}
}
return msg;
}
这里我还没有使用任何强制类型转换,因为我还没有找到有关强制类型转换为动态类型的有用信息。也许有人遇到同样的麻烦。
PS>如果有人知道相同的C#解决方案,我也将为此感到感谢。我的客户基于C#。
看来您正在尝试重制gson库之类的内容,这使我们能够
Message msg = gson.fromJson(request, Message.class);
演示:
class Message{
private short length;
private String text;
private String whatever;
@Override
public String toString() {
return "Message [length=" + length + ", text=" + text + ", whatever=" + whatever
+ "]";
}
}
public class Demo {
public static void main(String[] args) {
String request = "{'length':10, 'text':'foo bar'}";
Gson gson = new Gson();
Message msg = gson.fromJson(request, Message.class);
System.out.println(msg);
}
}
结果: Message [length=10, text=foo bar, whatever=null]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句