
io.ultreia.java4all.util.json.adapters.LeftOrRightContextAdapter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-util Show documentation
Show all versions of java-util Show documentation
Java Util api extends by Ultreia.io (not guava, nor commons)
The newest version!
package io.ultreia.java4all.util.json.adapters;
/*-
* #%L
* Java Util extends by Ultreia.io
* %%
* Copyright (C) 2018 - 2024 Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import com.google.auto.service.AutoService;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import io.ultreia.java4all.util.LeftOrRightContext;
import io.ultreia.java4all.util.json.JsonAdapter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Created at 22/04/2024.
*
* @author Tony Chemit - dev@tchemit.fr
* @since 1.1.17
*/
@AutoService(JsonAdapter.class)
public class LeftOrRightContextAdapter implements JsonSerializer>, JsonDeserializer>, JsonAdapter {
private static final String LEFT = "left";
private static final String RIGHT = "right";
@Override
public JsonElement serialize(LeftOrRightContext src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.add(LEFT, context.serialize(src.left()));
result.add(RIGHT, context.serialize(src.right()));
return result;
}
@Override
public LeftOrRightContext deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Type type = ((ParameterizedType) TypeToken.get(typeOfT).getType()).getActualTypeArguments()[0];
O left = context.deserialize(json.getAsJsonObject().get(LEFT), type);
O right = context.deserialize(json.getAsJsonObject().get(RIGHT), type);
return LeftOrRightContext.of(left, right);
}
@Override
public Class type() {
return LeftOrRightContext.class;
}
}