问题
How to use HazelcastJsonValue in the model class
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String name;
private HazelcastJsonValue value;
In the IMap I'm inserting the value some thing like this
map.put(i,new User(obj.getId,obj.getName,new HazelcastJsonValue(value.toString)));
Its throwing Serialization Exception for HazelcastJsonValue
How to resolve this isssue..?
回答1:
I can see 2 approaches to resolve this:
you either move away from using
HazelcastJsonValue
in the model class, so you use the string representation of the json, or anything that is serializable.you have to override the serialization method of this class by adding a
readObject()
and awriteObject()
method, and use a serializable representation of the json value while writing (string is a straightforward choice), and parse it while reading. Example (this just ran successfully for me):
package com.hazelcast.client.pncounter;
import com.hazelcast.core.HazelcastJsonValue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Whatever {
static class User implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private HazelcastJsonValue value;
public User(String id, String name, HazelcastJsonValue value) {
this.id = id;
this.name = name;
this.value = value;
}
private void writeObject(ObjectOutputStream out)
throws IOException {
out.writeObject(id);
out.writeObject(name);
out.writeObject(value.toString());
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
id = (String) in.readObject();
name = (String) in.readObject();
value = new HazelcastJsonValue((String) in.readObject());
}
}
public static void main(String[] args)
throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(new User("1", "name", new HazelcastJsonValue("{}")));
out.flush();
User user = (User) new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject();
}
}
Please refer to the Java SE documentation for details about customizing the serialization process.
来源:https://stackoverflow.com/questions/63007257/hazelcastjsonvalue-in-the-model-class