Gson将JSON数组反序列化为Object

时间:2015-07-23 11:38:40

标签: java android json gson deserialization

我有一个对象,我需要从JSON反序列化/解组(使用Gson)。我的问题是,我的JavaBean中的一个属性是一个复杂的对象,但需要从JSON数组中序列化:

JSON(有点类似):

{
    "name": "John Doe",
    "location": [
        9.560006,
        55.719474
    ],
}

目标类别(somwaht类似):

class UserLocation {
    private String name;
    private Location location;
    // ... "zero-args constructor", get'ers and set'ers
}
class Location {
    private double longitude;
    private double latitude;
    // ... "zero-args constructor", get'ers and set'ers
}

我的GsonBuilder配置为:

new GsonBuilder()
    .registerTypeAdapter(Location.class, new LocationTypeConverter())
    .create();

我的LocationTypeConverter看起来像这样:

public class LocationTypeConverter extends TypeAdapter<Location> implements JsonSerializer<Location>, JsonDeserializer<Location> {
    private static final int LONGITUDE_INDEX = 0;
    private static final int LATITUDE_INDEX = 1;

    @Override
    public JsonElement serialize(Location src, Type srcType, JsonSerializationContext context) {
        JsonArray array = new JsonArray();
        array.set(LATITUDE_INDEX, new JsonPrimitive(src.getLatitude()));
        array.set(LONGITUDE_INDEX, new JsonPrimitive(src.getLongitude()));
        return array;
    }

    @Override
    public Location deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
        JsonArray array = json.getAsJsonArray();
        return new Location(array.get(LATITUDE_INDEX).getAsDouble(), array.get(LONGITUDE_INDEX).getAsDouble());
    }

    @Override
    public void write(JsonWriter out, Location value) throws IOException {
        out.beginArray().value(value.getLongitude()).value(value.getLatitude()).endArray();
    }

    @Override
    public Location read(JsonReader in) throws IOException {
        in.beginArray();
        double longitude = in.nextDouble();
        double latitude = in.nextDouble();
        in.endArray();
        return new Location(longitude, latitude);
    }
}

但无济于事,因为我不断收到以下的Stacktrace:

     retrofit.RetrofitError: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 85 path $[0].location
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:377)
            at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
            at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
            at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at retrofit.Platform$Android$2$1.run(Platform.java:142)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 85 path $[0].location
            at retrofit.converter.GsonConverter.fromBody(GsonConverter.java:67)
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:362)
            at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
            at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
            at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at retrofit.Platform$Android$2$1.run(Platform.java:142)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 85 path $[0].location
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
            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.Gson.fromJson(Gson.java:810)
            at com.google.gson.Gson.fromJson(Gson.java:775)
            at retrofit.converter.GsonConverter.fromBody(GsonConverter.java:63)
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:362)
            at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
            at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
            at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at retrofit.Platform$Android$2$1.run(Platform.java:142)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 85 path $[0].location
            at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:189)

需要反序列化的两个类(包含Location实例和“wrap”对象本身的类都是简单的JavaBean(使用适当的set'er和get'er方法。

没有调用序列化,反序列化或读取的方法,所以我在这里做错了什么?

提前致谢,谢谢你的帮助!

编辑#1:添加目标类/ bean以澄清我正在尝试反序列化的对象图。

1 个答案:

答案 0 :(得分:2)

这是您编写的JSON所需的类:

MyObject {
    public String name;
    public float[] location;

    public float getLatitude() {
        if (location != null) return location[0];
        return 0;
    }
    public float getLongitude() {
        if (location != null) return location[1];
        return 0;
    }
}

虽然您编写的类将具有这样的JSON:

{
    "name": "John Doe",
    "location": {
        "longitude": 9.560006,
        "latitude": 55.719474
    }
}

最后,这是我对你的代码所做的测试,它运行正常!可能你只需要确保你总是使用相同的Gson对象(你从GsonBuilder.create获得的那个)?

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Location.class, new LocationTypeConverter())
            .setPrettyPrinting()
            .create();

    UserLocation userLocation = new UserLocation();
    userLocation.name = "ciao";
    userLocation.location = new Location(1.0, 3.0);
    String json = gson.toJson(userLocation);
    System.out.println(json);

    UserLocation newlocation = gson.fromJson(json, UserLocation.class);
    System.out.print(newlocation.location.getLatitude());