com.clickhouse.data.format.JsonStreamUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of clickhouse-data Show documentation
Show all versions of clickhouse-data Show documentation
Data processing utilities for ClickHouse
package com.clickhouse.data.format;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
/**
* Utility class for reading and writing objects in JSON format.
*/
public final class JsonStreamUtils {
private static final Gson gson = new Gson();
public static T readObject(InputStream input, Class clazz) throws IOException {
return readObject(input, StandardCharsets.UTF_8, clazz);
}
public static T readObject(InputStream input, Charset charset, Class clazz) throws IOException {
return readObject(new InputStreamReader(input, charset), clazz);
}
public static T readObject(Reader reader, Class clazz) throws IOException {
return gson.fromJson(reader, clazz);
}
public static T readObject(String json, Class clazz) throws IOException {
return gson.fromJson(json, clazz);
}
public static void writeObject(OutputStream output, T object) throws IOException {
writeObject(output, StandardCharsets.UTF_8, object);
}
public static void writeObject(OutputStream output, Charset charset, T object) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(output, charset);
writeObject(writer, object);
writer.flush();
}
public static void writeObject(Writer writer, T object) throws IOException {
gson.toJson(object, object == null ? Object.class : object.getClass(), gson.newJsonWriter(writer));
}
public static String toJsonString(Object object) {
return gson.toJson(object);
}
private JsonStreamUtils() {
}
}