com.clouway.friendlyserve.RsJson Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fserve Show documentation
Show all versions of fserve Show documentation
Friendly Serving HTTP Library.
package com.clouway.friendlyserve;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.stream.JsonWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
/**
* @author Miroslav Genov ([email protected])
*/
public class RsJson extends RsWrap {
public static final Gson GSON = new Gson();
public RsJson(JsonElement json) {
this(new RsWithBody(RsJson.streaming(json)));
}
public RsJson(final Response res) {
super(new RsWithType(res,"application/json; charset=utf-8"));
}
private static InputStream streaming(JsonElement src) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (JsonWriter writer = new JsonWriter(new OutputStreamWriter(baos, StandardCharsets.UTF_8))) {
GSON.toJson(src, writer);
} catch (IOException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(baos.toByteArray());
}
}