org.mule.modules.servicesource.RelationTargetDeserealizer.java Source code

Java tutorial

Introduction

Here is the source code for org.mule.modules.servicesource.RelationTargetDeserealizer.java

Source

/**
 * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
 *
 * The software in this package is published under the terms of the CPAL v1.0
 * license, a copy of which has been included with this distribution in the
 * LICENSE.md file.
 */

package org.mule.modules.servicesource;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.mule.modules.servicesource.model.RelationTarget;
import org.mule.modules.servicesource.model.RelationshipCycle;

import com.google.gson.Gson;
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.reflect.TypeToken;

/**
 * 
 * @author mariano.gonzalez@mulesoft.com
 *
 */
public class RelationTargetDeserealizer implements JsonDeserializer<RelationTarget> {

    @Override
    public RelationTarget deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        Gson gson = GsonFactory.getRawInstance();
        JsonObject object = json.getAsJsonObject();

        JsonElement relationshipsJson = object.remove("relationships");
        RelationTarget target = gson.fromJson(json, RelationTarget.class);

        if (relationshipsJson != null) {
            List<RelationshipCycle> relationships = null;

            if (relationshipsJson.isJsonArray()) {
                Type collectionType = new TypeToken<Collection<RelationshipCycle>>() {
                }.getType();
                relationships = gson.fromJson(json, collectionType);
            } else if (relationshipsJson.isJsonObject()) {
                if (!relationshipsJson.toString().trim().replaceAll(" ", "").equals("{}")) {
                    relationships = new ArrayList<RelationshipCycle>(1);
                    relationships.add(gson.fromJson(relationshipsJson, RelationshipCycle.class));
                }
            }

            target.setRelationships(relationships);
        }

        return target;
    }
}