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

Avoid gson de-serialize json string to to LinkedHashMap class members

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

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

但是,我有以下class

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 实例将有其 class 个成员作为 LinkedHashMap

如何强制反序列化 json 字符串,使 HashMap 成为 class 成员?

这是工作代码示例

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());
        }
    }
}

将您的字段声明为 HashMaps。如果不这样做,您将需要使用自定义解串器。

但如果您使用的是 Map,您为什么要关心它是 LinkedHashMap 还是 HashMap