Skip to content

Instantly share code, notes, and snippets.

@diyan
Last active June 28, 2023 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diyan/a791f0018bacd744232368ca87e5a4f5 to your computer and use it in GitHub Desktop.
Save diyan/a791f0018bacd744232368ca87e5a4f5 to your computer and use it in GitHub Desktop.
Bridge between Gson/GsonBuilder and Google HTTP Client.

Note that JsonHttpContent class from com.google.http-client/google-http-client-gson does not support the full feature set of Gson library.

Instead it just relies on the JsonParser provided by Gson.

Code snippet below provides a bridge between full featured Gson/GsonBuilder and Google HTTP Client.

See https://stackoverflow.com/questions/34690059/configuring-the-gsonfactory-of-google-http-client

See https://github.com/googleapis/google-http-java-client/tree/main/google-http-client-gson/src/main/java/com/google/api/client/json/gson

package com.example.project;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.lang.UnsupportedOperationException;

import com.google.api.client.http.AbstractHttpContent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public final class HttpJsonContent extends AbstractHttpContent {
	private static final Gson gson = new GsonBuilder()
			.create();
	
	private String jsonString;
	
	protected HttpJsonContent(String jsonString) {
		super("application/json; charset=UTF-8");
		// NOTE This is memory inefficient implementation
		this.jsonString = jsonString;
	}
	
	public static HttpJsonContent fromString(String jsonString) {
		return new HttpJsonContent(jsonString);
	}
	
	public static HttpJsonContent fromBytes(byte[] bytes) {
		return new HttpJsonContent(new String(bytes, StandardCharsets.UTF_8));
	}
	
	public static HttpJsonContent fromGson(Object gsonObject) {
		return new HttpJsonContent(gson.toJson(gsonObject));
	}
	
	public static HttpJsonContent fromJackson(Object jacksonObject) {
		throw new UnsupportedOperationException("Jackson JSON serializer is not yet supported.");
	}
	
	@Override
	public void writeTo(OutputStream out) throws IOException {
		try (Writer w = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
		    w.write(this.jsonString);
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment