首页 > 解决方案 > Java中获取JSON元素的数据类型

问题描述

我从 Kafka 队列中获得了一个 JSON 值,我想获得正确的数据类型以将其保存在数据库中。

值可以是:String、、intdouble数组。

如何自动检测正确的数据类型并从中创建 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类以将值转换为相应的数据类型并返回正确的对象?

感谢您的任何想法

标签: javaarraysjsonparsingprimitive-types

解决方案


你有没有尝试过:

//this instanciates an object of the getClass() method output
Object output = jsonValue.getClass().cast(jsonValue);

如果这不起作用,您可以尝试instanceof

if(jsonValue instanceof int){
    int output = (int) jsonValue;
}...

我希望这样做。


推荐阅读