用Gson反序列化地图密钥需要一个对象 [英] Deserializing map key with Gson expects an object

查看:68
本文介绍了用Gson反序列化地图密钥需要一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了错误:

Exception in thread "main" com.google.gson.JsonParseException: 
Expecting object found: "com.shagie.app.SimpleMap$Data@24a37368"

在尝试对使用非平凡键的Map进行反序列化时:

when trying to deseralize a Map that uses non-trivial keys:

package com.shagie.app;

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

import java.util.HashMap;

public class SimpleMap {
    public static void main(String[] args) {
        Wrapper w = new Wrapper();
        w.m.put(new Data("f", 1), new Data("foo", 3));
        w.m.put(new Data("b", 2), new Data("bar", 4));

        GsonBuilder gb = new GsonBuilder();
        gb.setPrettyPrinting();
        Gson g = gb.create();

        String json = g.toJson(w);

        System.out.println(json);

        w = g.fromJson(json, Wrapper.class);
        System.out.println(w.m.isEmpty());
    }

    static public class Wrapper {
        HashMap<Data, Data> m = new HashMap<Data, Data>();
    }

    static public class Data {
        String s;
        Integer i;
        public Data(String arg, Integer val) { s = arg; i = val; }
    }
}

这将序列化为json:

This serializes to the json:


{
  "m": {
    "com.shagie.app.SimpleMap$Data@24a37368": {
      "s": "foo",
      "i": 3
    },
    "com.shagie.app.SimpleMap$Data@66edc3a2": {
      "s": "bar",
      "i": 4
    }
  }
}

人们可以看到尝试序列化的密钥,但肯定不会以可以反序列化的方式看到.

One can see the key attempting to be serialized, but certainly not in a way that can be deserialized.

如何序列化此对象以便可以反序列化?

How does one serialize this object so that it can be deserialized?

推荐答案

在尝试解决此难题时,我发现了以下内容:

I found the following while trying to solve this puzzle: Issue 210: Cannot serialize or deserialize Maps with complex keys.

对于将来的任何互联网旅行者(例如我自己)...,您可以通过GsonBuilder上的enableComplexMapKeySerialization()方法在GSON 2. *中启用此功能.

For any internet travelers from the future (like myself)... you can enable this functionality in GSON 2.* with the enableComplexMapKeySerialization() method on GsonBuilder.

这是该方法的Javadoc .

启用后,地图将被序列化(并正确地反序列化)为[key,value]数组的数组:

When enabled, the map will be serialized (and correctly deserialized) as an array of [key, value] arrays:

{"m":[[{"s":"f", "i",1}, {"s":"foo", "i":3}], [{"s":"b", "i",2}, {"s":"bar", "i":4}]]}

这篇关于用Gson反序列化地图密钥需要一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆