繁体   English   中英

尝试从字符串解码 object 时出现 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());
}

So I create User object, convert it to String, save it to database on other device where I need to convert the object back to User object to change some stuff, convert to String again save to database and then be able to decode the User object再次在我的应用程序中。

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

线程“主”java.lang.ClassNotFoundException 中的异常:com.example.mikithenics.User

可能的解决方案是什么? 任何帮助表示赞赏。

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

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM