简体   繁体   English

确定Java中通用对象的类型

[英]Determine type of generic object in Java

I'm processing some JSON data, and I don't know what I will receive. 我正在处理一些JSON数据,但我不知道会收到什么。 For example, for key "TestKey" I might get a value of "MyValue" just as likely as I will get a value of 12345 or 10/10/2005. 例如,对于键“ TestKey”,我可能会获得“ MyValue”的值,就像获得12345或10/10/2005的值一样。

Is there an easy way in Java to determine the type of something generically classed as "Object"? 在Java中,是否有一种简单的方法来确定通常归类为“对象”的事物的类型?

I just want to be able to split it up into groups like int, double, date, string, etc. And I'm sure there is a classier way to do it than look at it with regular expressions. 我只希望能够将其分为int,double,date,string等组。而且我敢肯定,除了用正则表达式查看它之外,还有一种更为经典的方法。

Thanks 谢谢

You can't, your best choice is pass an extra field with some kind of data to identify the field type. 您不能,最好的选择是传递带有某些数据的额外字段以标识字段类型。 But that would be dirty. 但这太脏了。 The best option is always be sure of what kind of field will you get in the JSON, if you achieve that, then you will get compatibility with the JSON libraries like Gson. 最好的选择是始终确保您将在JSON中获得哪种字段,如果实现了这一点,那么您将获得与Gson等JSON库的兼容性。 If you don't, you are by your own and you will have to pass some kind of field like type:0 (where 0 is for int, 1 for double and so on...) and make a dirty switch to cast the field properly. 如果您不这样做,那么您就只能靠自己了,您将必须传递某种类型的字段,例如type:0 (其中0代表int,1代表double,依此类推...),然后进行肮脏的switch以投射适当地。

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

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