com.textkernel.tx.utilities.TxJsonSerializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of tx-java Show documentation
Show all versions of tx-java Show documentation
The official Java SDK for the Textkernel Tx v10 API.
The newest version!
// Copyright © 2023 Textkernel BV. All rights reserved.
// This file is provided for use by, or on behalf of, Textkernel licensees
// within the terms of their license of Textkernel products or Textkernel customers
// within the Terms of Service pertaining to the Textkernel SaaS products.
package com.textkernel.tx.utilities;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import java.lang.reflect.Type;
import java.time.LocalDate;
public class TxJsonSerializer {
private static final Gson _prettyGson;
private static final Gson _compactGson;
static {
_prettyGson = getBuilder().setPrettyPrinting().create();
_compactGson = getBuilder().create();
}
private static GsonBuilder getBuilder() {
return new GsonBuilder().registerTypeAdapter(LocalDate.class, new JsonDeserializer(){
@Override
public LocalDate deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
return LocalDate.parse(json.getAsJsonPrimitive().getAsString());
}
}).registerTypeAdapter(LocalDate.class, new JsonSerializer(){
@Override
public JsonElement serialize(LocalDate date, Type type, JsonSerializationContext context) {
return new JsonPrimitive(date.toString());
}
});
}
public static String serialize(Object o){
return serialize(o, false);
}
public static String serialize(Object o, boolean formatted){
return formatted ? _prettyGson.toJson(o) : _compactGson.toJson(o);
}
public static T deserialize(String json, Class classOfT) {
return _compactGson.fromJson(json, classOfT);
}
}