【问题标题】:Cannot deserialize array of unknown type using gson w/ java无法使用带有 java 的 gson 反序列化未知类型的数组
【发布时间】:2011-02-28 15:20:23
【问题描述】:

问题是数组中包含的数据类型直到运行时才知道。我创建了一个测试用例来说明我的问题。在涉及数组之前一切正常。

User user1 = new User(1, "one");
User user2 = new User(2, "two");

User [] users = {user1, user2};

Gson gson = new Gson();

// gson processing array of known a type. WORKS FINE
// observe use of brackets [] 
String toJson = gson.toJson(users, User[].class);
User [] newUsers = gson.fromJson(toJson, User[].class);
for(User user : newUsers) {
    System.out.println(user.toString());
}

// gson processing using reflection for single user. WORKS FINE
final Class<?> userType = Class.forName("com.abc.ws.GsonTest$User");
User user3 = new User(3, "three");
toJson = gson.toJson(user3, userType);
Object newUser = gson.fromJson(toJson, userType);
System.out.println(newUser.toString());

// gson processing using reflection for array of users. FAILS.
toJson = gson.toJson(users, WHAT_TO_PASS_HERE?); // it should be something like: userType[].class but that won't compile
Object newerUsers = gson.fromJson(toJson, WHAT_TO_PASS_HERE?); // it should be something like: userType[].class but that won't compile
for(User user : newerUsers) {
    System.out.println(user.toString());
}

顺便说一句:下面是完整的代码。

package com.abc;


import com.google.gson.Gson;


public class GsonTest {
    public static void main(String[] args) throws Exception {
        GsonTest.go();
}

    public static void go() throws Exception {
        User user1 = new User(1, "one");
        User user2 = new User(2, "two");

        User [] users = {user1, user2};

        Gson gson = new Gson();

        // gson processing array of known a type. Works fine
        // observe use of brackets [] 
        String toJson = gson.toJson(users, User[].class);
        User [] newUsers = gson.fromJson(toJson, User[].class);
        for(User user : newUsers) {
            System.out.println(user.toString());
        }

        // gson processing using reflection for single user. Works fine.
        final Class<?> userType = Class.forName("com.abc.GsonTest$User");
        User user3 = new User(3, "three");
        toJson = gson.toJson(user3, userType);
        Object newUser = gson.fromJson(toJson, userType);
        System.out.println(newUser.toString());

        // gson processing using reflection for array of users. Fails.

        toJson = gson.toJson(users, WHAT_TO_PASS_HERE?); // it should be something like: userType[].class but that won't compile
        Object newerUsers = gson.fromJson(toJson, WHAT_TO_PASS_HERE?); // it should be something like: userType[].class but that won't compile
        for(User user : newerUsers) {
            System.out.println(user.toString());
        }
    }

    public static class User {
        private int id;
        private String name;

        public User() { }

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String toString() {
            return "id: " + this.id + ", name: " + this.name;
        }
    }
}

【问题讨论】:

    标签: java arrays serialization gson


    【解决方案1】:

    尝试通过

    Array.newInstance(userType, 0).getClass()
    

    【讨论】:

      【解决方案2】:
      // serialized
      import java.beans.XMLDecoder;
      import java.beans.XMLEncoder;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.util.ArrayList;
      
      
      public class Serialization {
      
      
          private ArrayList<Student> obj;
          public Serialization() {
              obj = new ArrayList<Student>();
              obj.add(new Student("qwrr", "qwerr", "qwerr"));
              obj.add(new Student("zxcv", "zxcv", "zxcv"));
              obj.add(new Student("asdf", "asdf", "asdf"));
          }
      
          public void Save() throws Exception{
      
              FileOutputStream os = new FileOutputStream("cust.xml");
              XMLEncoder encoder = new XMLEncoder(os);
              encoder.writeObject(this.obj);
              encoder.close();
          }
      
          @SuppressWarnings("unchecked")
          public ArrayList<Student> Load() throws Exception{
              FileInputStream os = new FileInputStream("cust.xml");
              XMLDecoder decoder = new XMLDecoder(os);
              ArrayList<Student> p = (ArrayList<Student>)decoder.readObject();
              decoder.close();
              return p;
          }
      
          public static void main(String[] args) throws Exception {
      
              Serialization obj = new Serialization();
              obj.Save();
              ArrayList<Student> mas = obj.Load();
              for(Student st:mas)
              System.out.println(st);
      
          }
      
      }
      // student 
      public class Student {
      
          private String firstName;
          private String lastName;
          private String location;
      
          public Student(){
      
          }
      
          public Student(String first,String last, String location) {
              this.firstName = first;
              this.lastName = last;
              this.location = location;
          }
      
          public void setFirstName(String firstName) {
              this.firstName = firstName;
          }
      
          public String getFirstName() {
              return firstName;
          }
      
          public void setLastName(String lastName) {
              this.lastName = lastName;
          }
      
          public String getLastName() {
              return lastName;
          }
      
          public void setLocation(String location) {
              this.location = location;
          }
      
          public String getLocation() {
              return location;
          }
      
          @Override
          public String toString(){
              return this.firstName+" "+this.lastName+" "+this.location;
          }
      
      }
      // 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-03
        • 1970-01-01
        • 2013-09-16
        • 2017-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多