简体   繁体   中英

Gson dynamic class type

I am trying to deserialize JSON objects in my Java application using gson .

However, I cant figure how to dynamically apply the class type.

I have the class-name in a String

User user = gson.fromJson(userJSON, User.class);

How can I put String myClass as class type?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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