Serialize own class - java

i'm experiencing some problems with the serialization of Java and haven't found my Error.
I want to serialize my class, save it and read it again. This is the class i want to serialize:
public class MusicItem implements Serializable {
private static final long serialVersionUID = 6429052113846297403L;
public String title;
public String album;
public String artist;
public String art;
public String musiclocation;
}
And when i want to write it i get the following error:
08-07 14:21:37.723: W/System.err(9557): java.io.NotSerializableException: de.godev.gomusic.MainActivity
I hope you can help me.
Thanks in Advance,

The class which is not getting serialized is de.godev.gomusic.MainActivity
Please post the source of MainActivity class as well

If MusicItem is an inner class, you should make it static. An inner class maintains a reference to the object that it's contained in, and if you try to serialize it, the containing object has to be serialized as well.
To make a nested class static declare it with the static keyword:
public static class MusicItem implements ...

Related

How to serialize non primitive data using JAXB?

I want to serialize an object using JAXB. My class definitions looks like this:
#XmlRootElement
public class MyClass{
<<How do I annotate this one?>>
private xyz_type xyz;
#XmlElement(name = "unique")
private int unique;
}
public class xyz_type extends abc_type{
private qwe_tpe qwe;
public static final ert_type ARRAY = ert_type.ARRAY;
}
Thanks for your help in advance!
You need a customer XML adapter for marshalling complex data types.
See this guide: https://www.baeldung.com/jaxb - 6. Complex Data Types

jackson-databind "object is not an instance of declaring class"

I have been upgrading to a later version of jackson (i.e. from org.codehaus... to com.fasterxml...) and suddenly I am facing many weird errors. After hours of trying and adjusting I still cant get it to work so I am asking you guys if you can help me.
I have the following method:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("getTerminalsByIdAndLocation")
List<SearchResultDto> getTerminalsByIdAndLocation(#QueryParam("location") String location, #QueryParam("id") Integer id) throws BusinessException;
and that functions implementation just does a lookup in a repository.
The SearchResultDto looks like this:
#JsonIgnoreProperties(ignoreUnknown = true)
public class SearchResultDto implements Serializable {
private static final long serialVersionUID = 1L;
private TerminalId terminalId;
private Integer location;
private String streetNumber;
private String postalcoldeCity;
private Status status;
// getters and setters with no annotation or so
}
When I am now calling my method I am getting the following error:
Caused by: com.fasterxml.jackson.databind.JsonMappingException: object is not an instance of declaring class (through reference chain: java.util.ArrayList[0]-><long package>.SearchResultDto["terminalId"])
After a lot of trying I thought I will just remove the terminalId and then it changes to:
Caused by: com.fasterxml.jackson.databind.JsonMappingException: object is not an instance of declaring class (through reference chain: java.util.ArrayList[0]-><long package>AtmSearchResultDto["location"])
I am clueless, what is wrong here?
EDIT
I also tried using #JsonIgnore on everything except String streetNumber but then the same exception happens just for streetNumber
Long story short: I messed up my class path and there were two class loaders, the implementation of the REST method called a repository from the database module from where it got the instance from a different class loader. After adjusting my maven scopes and import types it is now working!
I had a similar issue for me the problem was that one of my POJOs was final. Removing the final keyword did the trick.
public final class AccessControlMap extends HashMap<Permission, Set<AccessType>>
//Before
public final class AccessType {
//After
public class AccessType {

Java work with class as collection to add items

This class below is my simple code which it is deployed ModelMarkets and I want to add item to this class List but I can't. Please help me to implement that.
My base class:
public class ModelMarkets extends RealmObject implements Parcelable {
#PrimaryKey
private String id;
private String marketId;
private String marketTitle;
...
}
And create a list from that and add an item to that class:
public class ModelMarketLists {
private List<ModelMarkets> modelMarkets = new ArrayList<>();
public ModelMarketLists(List<ModelMarkets> modelMarkets) {
this.modelMarkets = modelMarkets;
}
public ModelMarketLists(JSONArray lists) {
}
public void add(ModelMarketLists t){
/* modelMarkets.addAll(t); */
}
}
How can I add class collection data to modelMarkets as List ?
The type ModelMarketLists has a method public void add(ModelMarketLists t) but you are trying to invoke add(ModelMarkets), which will only work if ModelMarkets is a subtype of ModelMarketLists or if ModelMarketLists contains an overload like public void add(ModelMarkets modelMarkets).
Also, you should follow the Java naming conventions. Local variable names should start with a lower-case letter, be spelled in camel case, be long enough to be meaningful, reflect correct natural-language spelling, and reflect the semantics of the variable in the problem domain.

Overriding class signature in java

I have a class as follows in a .jar file (library file):
class A{
//someimplementation
}
I would like to make it to implements Serializable interface as follows:
class A implements Serializable {
//the same implementation as present in classA
}
I do not want to decompile the jar file, changing the class signature and then archiving it again after compilation.
Is there any way like writing hooks to achieve this? Kindly provide any pointers/suggestions.
My ultimate aim is to achieve implementing Serializable interface without modifying the jar file.
You can probably achieve this using Serialization Proxy Pattern (Effective Java 2nd edition Item 78)
A few links about the Pattern :
http://jtechies.blogspot.com/2012/07/item-78-consider-serialization-proxies.html
http://java.dzone.com/articles/serialization-proxy-pattern
Follow up: instance control in Java without enum
Make a new class that extends A and is Serializable. In order to avoid serialization errors, however, because A isn't serializable, you need to make a SerializationProxy that creates a new instance via constructor or factory method instead of the normal Java Serialization mechanism of explicitly setting the fields outside of any constructor.
public class MySerializableA extends A implements Serializable{
private final Foo foo;
private final Bar bar;
...
private Object writeReplace() {
return new SerializationProxy(this);
}
//this forces us to use the SerializationProxy
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use Serialization Proxy instead.");
}
//this private inner class is what actually does our Serialization
private static class SerializationProxy implements Serializable {
private final Foo foo;
private final Bar bar;
...
public SerializationProxy(MySerializableA myA) {
this.foo = myA.getFoo();
this.bar = myA.getBar();
...//etc
}
private Object readResolve() {
return new MySerializableA(foo, bar,...);
}
}
}
The only downside is when you want to serialize an A, you will have to wrap it in a MyA. but when deserializing, the cast to A will work fine.

Convert outdated stored class to updated class

I am facing a problem with the classes. I store data in Serializable classes as a Java Object, not as a series of variables at some places. However, when I make changes to the class in question, Java would immediately throw an Error.
For example this is an old class:
class Demo implements Serializable{
private int a; private int b; int c;
public void doSomething(){}
public void doSomethingElse(){}
}
Which gets updated to:
class Demo implements Serializable{
private int a; private private int b; private int c; private String x; private String y; private String z;
public void doSomething(){}
public void doSomethingElse(){}
public void doAnotherThing(){}
public void doYetAnotherThing(){}
}
Is there a way to convert the old Object to the new one seamlessly without having to name the new class as DemoNew or something and then transferring the values one by one?
Regards.
That's what the serialVersionUID is for. If you declare it in your new class, and it has the same value as it had when the object was serialized, then Java will know that the new class is still compatible with the old class, and will initialize a, b, and c (and will leave the other fields to their default value).
So, get the old serialVersionUID from the error being thrown, and add this field to the class:
private static final long serialVersionUID = ...;
Of course, that only works if the new class is effectively still compatible with the old one. If you renamed or removed fields, then you'll have to make it compatible by explicitely reading the object as it was at the time of serialization.
If I were you, I would stop using serialization as a long-term persistence mechanism. Choose an easily migratable format instead: a database, JSON, or XML for example.

Categories