当前,如果我想避免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());
}
}
}
将您的字段声明为HashMap
s。缺少这些,您将需要使用自定义解串器。
但是,如果您正在使用Map
,为什么还要关心它是aLinkedHashMap
还是a HashMap
?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句