String []数组将在Google GSON中转换为List

时间:2018-02-05 13:29:29

标签: java json hashmap gson

我可以在下面的例子中知道我的String[]数组被转换为List Array的原因:

public static void main(String[] args) {
     String s1="one,two";
     Map<String, String[]> m =new HashMap<String, String[]>();
     m.put("attribute" , s1.split(","));
     String[] s = ( String[]) m.get("attribute"); // this works fine 

    Gson gson=new Gson();
    String se = gson.toJson(m);
      HashMap hm = gson.fromJson(se, HashMap.class);
      String[] sArray  = ( String[]) hm.get("attribute"); //this give exception cant convert list into String array 
      List lst  = ( List) hm.get("attribute"); // this works fine 

}

我正在使用Google的GSON Class。

1 个答案:

答案 0 :(得分:0)

Gson类型反序列化数组JSON类型是List。如果你想要它创建一个基本类型的数组,你需要编写自己的对象,这个对象包含一个名为'attribute'的基本数组

public class MyObject {
    protected String[] attribute;
}

并为您的类型提供序列化器/反序列化器。请参阅:https://google.github.io/gson/apidocs/com/google/gson/GsonBuilder.html#registerTypeAdapter-java.lang.reflect.Type-java.lang.Object-

相关问题