All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.netty.marshallers.JsonMapMarshaller Maven / Gradle / Ivy

There is a newer version: 1.6.8
Show newest version
package org.zodiac.netty.marshallers;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.zodiac.commons.util.serialize.JsonUtil;
import org.zodiac.sdk.toolkit.marshallers.Marshaller;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;

final class JsonMapMarshaller implements Marshaller, ByteBuf> {

    private final ObjectMapper mapper;

    JsonMapMarshaller() {
        this(null);
    }

    JsonMapMarshaller(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map read(ByteBuf data, Object[] hints) throws IOException {
        try (final ByteBufInputStream in = new ByteBufInputStream(data)) {
            return null != mapper ? mapper.readValue((DataInput) in, Map.class) :
                JsonUtil.readMap((DataInput) in, String.class, Object.class);
        }
    }

    @Override
    public void write(Map obj, ByteBuf into, Object[] hints) throws IOException {
        try (final ByteBufOutputStream out = new ByteBufOutputStream(into)) {
            if (null != mapper) {
                mapper.writeValue((DataOutput) out, obj);
            } else {
                JsonUtil.writeValue((DataOutput) out, obj);
            }
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy