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

org.jetlinks.rule.engine.defaults.codec.JsonArrayCodec Maven / Gradle / Ivy

package org.jetlinks.rule.engine.defaults.codec;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.Unpooled;
import org.jetlinks.rule.engine.api.Payload;
import org.jetlinks.rule.engine.api.codec.Codec;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.function.Function;

public class JsonArrayCodec implements Codec {

    private final Class type;

    private final Function, R> mapper;

    private JsonArrayCodec(Class type, Function, R> mapper) {
        this.type = type;
        this.mapper = mapper;
    }

    public static  JsonArrayCodec> of(Class type) {
        return of(type, Function.identity());
    }

    public static  JsonArrayCodec of(Class type, Function, R> function) {
        return new JsonArrayCodec<>(type, function);
    }

    @Override
    public R decode(@Nonnull Payload payload) {
        return mapper.apply(JSON.parseArray(payload.bodyAsString(), type));
    }

    @Override
    public Payload encode(R body) {
        return () -> Unpooled.wrappedBuffer(JSON.toJSONBytes(body));
    }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy