尝试从 String 解码对象时出现 ClassNotFoundException

ClassNotFoundException when trying to decode object from String

好的,我得到了这个 Android Studio 应用,用户 class

public class User{
   int age;
   String name;
   int yearOfBirth;
}

然后我得到了这两个方法

public static Object fromString(String s) throws IOException,ClassNotFoundException {
    byte [] data = Base64.getDecoder().decode(s);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
    Object o  = ois.readObject();
    ois.close();
    return o;
}

public static String toString(Serializable o) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);
    oos.close();
    return Base64.getEncoder().encodeToString(baos.toByteArray());
}

所以我创建了 User 对象,将其转换为 String,将其保存到其他设备上的数据库中,我需要将对象转换回 User 对象以更改一些内容,再次转换为 String 保存到数据库然后能够再次解码我的应用程序中的用户对象。

问题是在服务器端尝试解码字符串时出现此异常

Exception in thread "main" java.lang.ClassNotFoundException: com.example.mikithenics.User

可能的解决方案是什么?感谢任何帮助。

您可以像这样使用 Google Gson 库对其进行序列化:

Gson gson = new Gson();

String jsonString = gson.toJson(userObject);

并像这样反序列化:


Gson gson = new Gson();

User userObject = gson.fromJson(userJsonString, User.class);

要使用 Gson 库,请将其放入您的应用程序 build.gradle 文件中,在依赖项内:

implementation 'com.google.code.gson:gson:2.8.6'