java - Java中获取JSON元素的数据类型
问题描述
我从 Kafka 队列中获得了一个 JSON 值,我想获得正确的数据类型以将其保存在数据库中。
值可以是:String
、、int
或double
数组。
如何自动检测正确的数据类型并从中创建 Java 对象?
我的第一步:
检查 json 是否为数组:
if (jsonValue.isJsonPrimitive()) {
// create new Object
//ToDo need to parse int, double not only to string
new ValueObject(time,jsonValue.getAsString);
} else if (jsonValue.isJsonArray()) {
//create new Object
//ToDo need to parse int, double string
new ValueObject(time,jsonValue.getAsJsonArray());
}
如何设计ValueObject
类以将值转换为相应的数据类型并返回正确的对象?
感谢您的任何想法
解决方案
你有没有尝试过:
//this instanciates an object of the getClass() method output
Object output = jsonValue.getClass().cast(jsonValue);
如果这不起作用,您可以尝试instanceof
:
if(jsonValue instanceof int){
int output = (int) jsonValue;
}...
我希望这样做。
推荐阅读
- ios - XCUITest 框架中是否有任何同步方式来测试具有大数据的 UITableview?
- c# - 使用 IMethodCallTranslator 的具有任意数量参数的自定义函数
- javascript - 如何使其适用于 html 表中特定类的转换持续时间
- c - Linux/POSIX:timer_settime - 无法从定时器生成的线程中解除定时器
- r - 用新值替换列中的多个值
- ionic-framework - 不同幻灯片中的不同列表同时滚动
- jquery - 在按钮单击时使用 ajax 调用数据在第二次单击时不能在同一个按钮上工作
- java - Swagger codegen 生成重复变量
- arrays - 从 VBA 函数返回数组的正确方法
- jmeter - jMeter:将多行从 CSV 文件加载到 HTTP 正文中