java - Gson 无法反序列化 List<Serialized>

标签 java json gson

我正在尝试将从服务器获取的 JSON 反序列化为其原始 POJO 形式。我知道原始对象(我有服务器代码的来源),但似乎我丢失了一些东西。

这是我可以组装的最小代码示例,它说明了我的问题:

package mycompany.mypackage;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;

public class GsonSerializeTest {

    /* main method to illustrate the problem */
    public static void main(String[] args) {
        Serializable[] identifiers= {"ITEM",12345678,"abc.def.ghijkl.mnopqr",87654321};
        EntityUid uid = new GsonSerializeTest().new EntityUid(identifiers);
        Gson converter = new GsonBuilder().registerTypeAdapter(Serializable.class, new GsonSerializeTest().new SerializableInstanceCreator()).create();
        String json = converter.toJson(uid);
        System.out.println("Converted to string: " + json);
        EntityUid uid2 = converter.fromJson(json, EntityUid.class); // ERROR
        System.out.println("Converted back to object: " + uid2);
    }

    /* the POJO that gets serialized and fails while deserializing */
    public class EntityUid implements Serializable {
        private final List<Serializable> identifier = new ArrayList<Serializable>();

        public EntityUid(final Serializable... identifier) {
            for (Serializable partialIdentifier : identifier) {
                this.identifier.add(partialIdentifier);
            }
        }
    }

    /* Class for generating Serializable instances */
    public class SerializableInstanceCreator implements InstanceCreator<Serializable> {
        public Serializable createInstance(Type arg0) {
            return new String();
        }
    }
}

这会准备 EntityUid 对象,将其序列化(就像服务器所做的那样):

Converted to string: {"identifier":["ITEM",12345678,"abc.def.ghijkl.mnopqr",87654321]}

然后尝试将其反序列化为原始对象,但失败并显示以下内容:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 17
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
    at com.google.gson.Gson.fromJson(Gson.java:803)
    at com.google.gson.Gson.fromJson(Gson.java:768)
    at com.google.gson.Gson.fromJson(Gson.java:717)
    at com.google.gson.Gson.fromJson(Gson.java:689)
    at mycompany.mypackage.GsonSerializeTest.main(GsonSerializeTest.java:19)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 17
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
    ... 10 more

有人可以向我指出我可能缺少什么吗?预先非常感谢!

最佳答案

请阅读Serializing and Deserializing Collection with Objects of Arbitrary Types

下面的代码可以工作。

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonSerializeTest {

    /* main method to illustrate the problem */
    public static void main(String[] args) {
        Object[] identifiers= {12345678,"ITEM","abc.def.ghijkl.mnopqr",87654321};
        EntityUid uid = new EntityUid(identifiers);
        Gson converter = new GsonBuilder().create();
        String json = converter.toJson(uid);
        System.out.println("Converted to string: " + json);
        EntityUid uid2 = converter.fromJson(json, EntityUid.class); // ERROR
        System.out.println("Converted back to object: " + uid2);
    }

    /* the POJO that gets serialized and fails while deserializing */
    public static class EntityUid  {
        private final List<Object> identifier = new ArrayList<Object>();

        public EntityUid(final Object... identifier) {
            for (Object partialIdentifier : identifier) {
                this.identifier.add(partialIdentifier);
            }
        }

        @Override
        public String toString() {
            return "EntityUid [identifier=" + identifier + "]";
        }


    }
}

关于java - Gson 无法反序列化 List<Serialized>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18461046/

相关文章:

java - 无法在 hadoop 2.4.0 上运行 MapReduce 作业

android - Json 字符串到 Realm 对象,最快的方法

json - Swift 3-JSON解析

java - 如何在android volley中隐藏Url或参数值?

json - Grails GSON JSON View

java - 如何从服务器外部运行的 Java 客户端访问 WebSphere 身份验证别名信息?

java - 为什么我会得到 "Illegal generic type for instanceof"?

java - 如何在 Java 中使用刷新 token 获取访问 token ?

java - com.google.gson.Gson 类因 javax.crypto.SecretKey 而失败?

java - 反序列化Json,结构相同但字段名不同