hydra.langs.json.JsonSerde Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hydra-java Show documentation
Show all versions of hydra-java Show documentation
The Hydra language for strongly-typed transformations
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);
}
}