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

com.stripe.model.SourceDeserializer Maven / Gradle / Ivy

There is a newer version: 26.13.0-beta.1
Show newest version
package com.stripe.model;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.HashMap;

public class SourceDeserializer implements JsonDeserializer {

	private void populateMapFromJSONObject(Map objMap, JsonObject jsonObject) {
		for (Map.Entry entry: jsonObject.entrySet()) {
			String key = entry.getKey();
			JsonElement val = entry.getValue();
			String value;
			if (!val.isJsonNull()) {
				value = entry.getValue().getAsString();
				objMap.put(key, value);
			}
		}
	}

	public Source deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {
		Gson gson = new GsonBuilder()
			.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
			.create();

		if (json.isJsonNull()) {
			return null;
		}

		if (!json.isJsonObject()) {
			throw new JsonParseException("Source type was not an object, which is problematic.");
		}

		JsonObject sourceAsJsonObject = json.getAsJsonObject();

		// Get the `type` out of the response.
		String type = sourceAsJsonObject.getAsJsonPrimitive("type").getAsString();

		// Populate the `typeData` from the `type` property.
		Map typeData = new HashMap();
		populateMapFromJSONObject(typeData, sourceAsJsonObject.getAsJsonObject(type));

		// Remove the `type` property.
		sourceAsJsonObject.remove(type);
		Source parsedData = gson.fromJson(json, typeOfT);
		parsedData.setTypeData(typeData);

		return parsedData;
	}
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy