Reputation: 314
Alright so I've got this Android Studio app with user class
public class User{
int age;
String name;
int yearOfBirth;
}
And then I've got this two methods
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 in my app again.
Problem is when trying to decode the String on the server side I'm getting this exception
Exception in thread "main" java.lang.ClassNotFoundException: com.example.mikithenics.User
What could be the possible solution ? Any help is appreciated.
Upvotes: 0
Views: 409
Reputation: 68
You can serialize this using Google Gson lib like this:
Gson gson = new Gson();
String jsonString = gson.toJson(userObject);
And deserialize like this:
Gson gson = new Gson();
User userObject = gson.fromJson(userJsonString, User.class);
To use Gson lib, put this in your app build.gradle file, inside dependencies:
implementation 'com.google.code.gson:gson:2.8.6'
Upvotes: 1