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

hydra.langs.json.JsonSerde Maven / Gradle / Ivy

There is a newer version: 0.8.0
Show newest version
package hydra.langs.json;

import com.cedarsoftware.util.io.JsonReader;
import com.cedarsoftware.util.io.JsonWriter;
import hydra.Flows;
import hydra.compute.Coder;
import hydra.compute.Flow;
import hydra.json.Value;

import java.util.HashMap;
import java.util.Map;

/**
 * A bidirectional coder between Hydra's native JSON values and strings (via json-io).
 */
public class JsonSerde extends Coder {
    private static final Map WRITER_ARGS = new HashMap() {{
        put(JsonWriter.TYPE, false);
        put(JsonWriter.PRETTY_PRINT, false);
        //put(JsonWriter.SKIP_NULL_FIELDS, true);
    }};

    public JsonSerde() {
        super(JsonSerde::encode, JsonSerde::decode);
    }

    /**
     * Encode a JSON value to a string.
     */
    public static  Flow encode(Value value) {
        return Flows.map(JsonIoCoder.encode(value),
                raw -> JsonWriter.objectToJson(JsonIoCoder.normalizeEncoded(raw), WRITER_ARGS));
    }

    /**
     * Decode a JSON value from a string.
     */
    public static  Flow decode(String value) {
        Object json;
        try {
            json = JsonReader.jsonToJava(value);
        } catch (Exception e) {
            return Flows.fail("JSON parse error", e);
        }

        return JsonIoCoder.decode(json);
    }
}