ezbake.services.search.utils.BooleanSerializer.java Source code

Java tutorial

Introduction

Here is the source code for ezbake.services.search.utils.BooleanSerializer.java

Source

/*   Copyright (C) 2013-2015 Computer Sciences Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

package ezbake.services.search.utils;

import com.google.gson.*;

import java.lang.reflect.Type;

public class BooleanSerializer implements JsonSerializer<Boolean>, JsonDeserializer<Boolean> {

    @Override
    public JsonElement serialize(Boolean arg0, Type arg1, JsonSerializationContext arg2) {
        return new JsonPrimitive(arg0 ? 1 : 0);
    }

    @Override
    public Boolean deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
            throws JsonParseException {
        if (arg0.getAsJsonPrimitive().isBoolean()) {
            return arg0.getAsBoolean();
        }
        if (arg0.getAsJsonPrimitive().isString()) {
            return Boolean.parseBoolean(arg0.getAsString());
        } else {
            return arg0.getAsInt() == 1 ? true : false;
        }
    }
}