【问题标题】:There is a way to know which type json is represent?有一种方法可以知道 json 代表的是哪种类型?
【发布时间】:2012-04-30 19:11:25
【问题描述】:

假设我有两个对象:Person 和 ReqSingUp,而 ReqSingUp 包含 Person。

现在如果我尝试:

Person p=new Person("dan","lala");
ReqSingUp reqSingUp=new ReqSingUp(p);
String s = gson.toJson(reqSingUp,ReqSingUp.class);
Object o = gson.fromJson(s, Object.class);

if (o instanceof ReqSingUp) {
    System.out.println("it's ReqSingUp");
}
if (o instanceof Person ) {
    System.out.println("it's person");
}

它不满足任何条件(不满足 instanceof ReqSingUpinstanceof Person )。

有没有办法知道它是哪种类型?

提前致谢。

【问题讨论】:

标签: java json gson


【解决方案1】:

不,没有办法直接知道。

这是因为包含在 JSon 文件中的信息不直接包含关于在其中序列化的对象的任何类型信息。这就是为什么您通常在读取 JSon 文件时提供类的原因,如

fromJSon(myObject, MyClass.class)

即使在读取任意类型或泛型对象的集合时,这确实会产生问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多