Java Гсон JSON Сериализация и десериализация с полиморфами c Объекты - PullRequest
0 голосов
/ 01 апреля 2020

Я новичок в java и Гсон. В настоящее время мне нужно извлечь JSON, поэтому я столкнулся с Gson в качестве отправной точки. Я пытаюсь сериализовать и десериализовать массив Polymorphi c JSON внутри объекта JSON. В качестве примера я использовал следующее:

JSON:

{
   "pet_shop_name":"Pet Shop",
   "animal_list":[
      {
         "playsCatch":true,
         "name":"dog1",
         "type":"dog"
      },
      {
         "playsCatch":false,
         "name":"dog2",
         "type":"dog"
      },
      {
         "chaseLaser":false,
         "name":"cat1",
         "type":"cat"
      }
   ]
}

My Java Класс:

public class pet_shop {
    String pet_shop_name;
    List<Animal_list> animal_list;

    public pet_shop(String pet_shop_name, List<Animal_list> animal_list) {
        this.pet_shop_name = pet_shop_name;
        this.animal_list = animal_list;
    }

    public static class Animal_list {
        String name;
        String type;

        public Animal_list(String name, String type) {
            this.name = name;
            this.type = type;
        }

        public static class Dog extends Animal_list {
            private boolean playsCatch;

            public Dog(String name, boolean playsCatch) {
                super(name, "dog");
                this.playsCatch = playsCatch;
            }
        }

        public static class Cat extends Animal_list {
            private boolean chaseLaser;

            public Cat(String name, boolean chaseLaser) {
                super(name, "cat");
                this.chaseLaser = chaseLaser;
            }
        }
    }
}

My Java Функция:

public static void deserialize_polymorphic_objects_in_object() {
    // Serialize
    List<pet_shop.Animal_list> animal_list = new ArrayList<>();
    animal_list.add(new pet_shop.Animal_list.Dog("dog1", true));
    animal_list.add(new pet_shop.Animal_list.Dog("dog2", false));
    animal_list.add(new pet_shop.Animal_list.Cat("cat1", false));
    RuntimeTypeAdapterFactory<pet_shop.Animal_list> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
            .of(pet_shop.Animal_list.class, "type")
            .registerSubtype(pet_shop.Animal_list.Dog.class, "dog")
            .registerSubtype(pet_shop.Animal_list.Cat.class, "cat");

    pet_shop petShop = new pet_shop(
            "Pet Shop",
            animal_list
    );
    // Gson gson = new GsonBuilder().registerTypeAdapterFactory(runtimeTypeAdapterFactory).create();
    Gson gson = new Gson();
    String toJson = gson.toJson(petShop);

    // Deserialize
    Type listType = new TypeToken<List<pet_shop.Animal_list>>(){}.getType();
    pet_shop fromJson = gson.fromJson(toJson, pet_shop.class);
}

У меня есть несколько вопросов по этой части: Если я использовал

Gson gson = new GsonBuilder().registerTypeAdapterFactory(runtimeTypeAdapterFactory).create();

, то это приведет к ошибка

Exception in thread "main" com.google.gson.JsonParseException: cannot serialize pet_shop$Animal_list$Dog because it already defines a field named type

и я хотел бы знать причину.

И еще вопрос: как мне снова отобразить строку JSON в класс Java с помощью пользовательского расширенного класса? Пожалуйста помоги. Я застрял в этом в течение нескольких дней. Спасибо!

...