[英]Gson dynamic class type
I am trying to deserialize JSON
objects in my Java application using gson
. 我正在尝试使用gson
在Java应用程序中反序列化JSON
对象。
However, I cant figure how to dynamically apply the class type. 但是,我不知道如何动态地应用类类型。
I have the class-name in a String
我在String
有类名
User user = gson.fromJson(userJSON, User.class);
How can I put String myClass
as class type? 如何将String myClass
为类类型?
Class<?> cls = Class.forName(className);
但是您的className应该是完全合格的-即com.mycompany.MyClass
I believe what is suggested in the previous answer is perfectly OK. 我相信上一个答案中所建议的完全可以。 Just to avoid all confusions and make it much obvious, here is the full code: 只是为了避免所有混乱并使它更加明显,这是完整的代码:
package com.test;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class TestGSON {
public static void main(String[] args) {
Gson gson = new Gson();
try{
Object fromJson = gson.fromJson("{\"name\":\"Dharam\"}", Class.forName("com.test.MyClass"));
if(fromJson instanceof MyClass){
System.out.println(fromJson);
}
} catch (JsonSyntaxException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyClass {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "MyClass [name=" + name + "]";
}
}
Output from the above code: 上面代码的输出:
MyClass [name=Dharam]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.