避免gson将json字符串反序列化为LinkedHashMap类成员

时间:2015-01-22 20:16:40

标签: java json gson

目前,如果我想避免gson从反序列化json字符串到LinkedHashMap,我会使用以下代码

HashMap<Integer, String> map = gson.fromJson(json_string,  new TypeToken<HashMap<Integer, String>>(){}.getType());

但是,我有以下课程

public static class Inventory {
    public Map<Integer, String> map1 = new HashMap<Integer, String>();
    public Map<Integer, String> map2 = new HashMap<Integer, String>();
}

如果我使用Inventory result = gson.fromJson(json_string, Inventory.class);,我的Inventory实例的类成员将为LinkedHashMap

如何强制对json字符串进行反序列化,让HashMap成为类成员?

这是工作代码示例

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author yccheok
 */
public class Gson_tutorial {
    public static class Inventory {
        public Map<Integer, String> map1 = new HashMap<Integer, String>();
        public Map<Integer, String> map2 = new HashMap<Integer, String>();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        {
            Map<Integer, String> map= new HashMap<Integer, String>();
            map.put(2, "cake");

            final Gson gson = new GsonBuilder().create();
            final String json_string = gson.toJson(map);
            // {"2":"cake"}
            System.out.println(json_string);

            HashMap<Integer, String> result = gson.fromJson(json_string,  new TypeToken<HashMap<Integer, String>>(){}.getType());
            // class java.util.HashMap
            System.out.println(result.getClass());
        }

        {
            Inventory inventory = new Inventory();
            inventory.map1.put(2, "cake");
            inventory.map2.put(3, "donut");

            final Gson gson = new GsonBuilder().create();
            final String json_string = gson.toJson(inventory);
            // {"map1":{"2":"cake"},"map2":{"3":"donut"}}
            System.out.println(json_string);

            Inventory result = gson.fromJson(json_string,  Inventory.class);
            // class java.util.LinkedHashMap
            System.out.println(result.map1.getClass());
            // class java.util.LinkedHashMap
            System.out.println(result.map2.getClass());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

将您的字段声明为HashMap s。如果没有这样做,您将需要使用自定义反序列化器。

但如果你正在使用Map,为什么要关心它是LinkedHashMap还是HashMap