目前,如果我想避免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());
}
}
}发布于 2015-01-22 20:20:14
将您的字段声明为HashMaps。否则,您将需要使用自定义反序列化器。
但是如果你使用的是Map,你为什么要关心它是LinkedHashMap还是HashMap
https://stackoverflow.com/questions/28097902
复制相似问题