簡體   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