首页 > 解决方案 > 模型类中的 HazelcastJsonValue

问题描述

如何在模型类中使用 HazelcastJsonValue

public class User implements Serializable{
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String id;
    private String name;
    private HazelcastJsonValue value; 

在 IMap 中,我正在插入类似这样的值

map.put(i,new User(obj.getId,obj.getName,new HazelcastJsonValue(value.toString)));

它为 HazelcastJsonValue 抛出序列化异常

如何解决这个问题..?

标签: javahazelcast

解决方案


我可以看到解决此问题的两种方法:

  1. 您要么不再HazelcastJsonValue在模型类中使用,而是使用 json 的字符串表示形式,或者任何可序列化的东西。

  2. readObject()您必须通过添加 a和 a方法来覆盖此类的序列化方法writeObject(),并在写入时使用 json 值的可序列化表示(字符串是一个简单的选择),并在读取时对其进行解析。示例(这对我来说刚刚成功运行):

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();
    }
}

有关自定义序列化过程的详细信息,请参阅Java SE 文档


推荐阅读