【问题标题】:ClassNotFoundException when trying to decode object from String尝试从 String 解码对象时出现 ClassNotFoundException
【发布时间】:2020-05-05 22:38:04
【问题描述】:

好的,我已经有了这个带有用户类的 Android Studio 应用

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 对象。

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

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

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

【问题讨论】:

  • “可能的解决方案是什么?” ——嗯,目前最好的解决方案是停止使用ObjectInputStreamObjectOutputStream。使用 JSON、XML 或其他方式对数据进行中性、与环境无关的编码。特别是,使用对象序列化进行跨 VM 数据交换(Android 的 Dalvik 或 ART,与您服务器上的 JVM 对比)确实不是一个好计划。但是,除此之外,如果您打算反序列化服务器上​​的 User 对象,则您的服务器需要该类。
  • 是的,我知道它需要“com.example.mikithenics”这个类。这部分是问题所在。我可以将整个对象解码并编码为 JSON 吗?
  • JSON 中的“O”代表“o​​bject”(JavaScript 对象表示法)。 { "age": 19, "name": "Martin Lukas", "yearOfBirth": 2001 } 将是 User 对象的一种 JSON 表示形式。
  • 是的,我知道 JSON 的样子和它的含义,虽然我不知道如何将 Java 对象转换为 JSON,但实际的 User 类有 50 个变量,我只能考虑一一分配User.name= JSON.getString("name");等
  • 有JSON解析和创建的库,如Moshi

标签: java android android-studio base64 classnotfoundexception


【解决方案1】:

您可以像这样使用 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'

【讨论】:

  • 谢谢 ;) 可能是最快的解决方案
猜你喜欢
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多