使用gson动态地将对象反序列化为子类型

83qze16e  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(212)

我有一个基类

public class Box<T> {
    private T entity;

    public T getEntity() {
        return entity;
    }

    void setEntity(T entity) {
        this.entity = entity;
    }
}

它有2个实现。

// Class Person
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
// Class Machine
public class Machine {
    private String macAddress;
    private String type;

    public Machine(String macAddress, String type) {
        this.macAddress = macAddress;
        this.type = type;
    }
}

如果我想序列化A类或B类对象,我将这样做

Type typeTokenPerson = new TypeToken< Box <Person>>() {}.getType();
String userJson = gson.toJson(boxWithPersonObject, typeTokenPerson);

但是这里的问题是我需要在编译时知道类型。我有一个用例,在编译时我不知道这个,换句话说,我有一个json,我想把它反序列化成Person或者Animal,我想在运行时根据一些条件来做这个。有没有办法用Gson来做这个?
示例:假设我们有一个这样的json

{
  "entity": {
    "name": "ABC",
    "age": 10
  }
}

这是Person类型。我想将它反序列化为Box类型的对象

hof1towb

hof1towb1#

Gson可以这样做。

package com.example.demo;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.time.Duration;
import java.time.LocalDateTime;

public class GsonDemo {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private <T> Box<T> parseResponse(String responseData) {

        Gson gson = new Gson();
        Type jsonType = new TypeToken<Box<T>>() {
        }.getType();
        Box<T> result = gson.fromJson(responseData, jsonType);

        return result;
    }

    @Test
    public void test() {
        LocalDateTime start = LocalDateTime.now();
        try {
            String json = "{  \"entity\": {  \"name\": \"ABC\",    \"age\": 10 }}";
            Box<Person> objectBox = parseResponse(json);
            System.out.println(objectBox);
            String json2 = "{\n  \"entity\": {  \"macAddress\": \"DEF\",   \"type\": \"def\" }}";
            Box<Machine> objectBox2 = parseResponse(json2);
            System.out.println(objectBox2);
        } catch (Exception e) {
            logger.error("Error", e);
        }
        LocalDateTime end = LocalDateTime.now();
        logger.info("Cost time {}", Duration.between(start, end).toMillis() + "ms");
    }

    public class Box<T> {
        private T entity;

        public T getEntity() {
            return entity;
        }

        void setEntity(T entity) {
            this.entity = entity;
        }

        @Override
        public String toString() {
            return "Box{" + "entity=" + entity + '}';
        }
    }

    public class Person {
        private String name;
        private Integer age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
        }
    }

    public class Machine {
        private String macAddress;
        private String type;

        public Machine(String macAddress, String type) {
            this.macAddress = macAddress;
            this.type = type;
        }

        public String getMacAddress() {
            return macAddress;
        }

        public void setMacAddress(String macAddress) {
            this.macAddress = macAddress;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        @Override
        public String toString() {
            return "Machine{" + "macAddress='" + macAddress + '\'' + ", type='" + type + '\'' + '}';
        }
    }
}

相关问题