001/*
002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo
018 */
019package org.nuxeo.ecm.automation.client.jaxrs.spi.marshallers;
020
021import java.io.IOException;
022
023import org.nuxeo.ecm.automation.client.jaxrs.spi.JsonMarshaller;
024
025import com.fasterxml.jackson.core.JsonGenerator;
026import com.fasterxml.jackson.core.JsonParser;
027
028/**
029 * Marshaller for the default ObjectCodec for the java Number abstract class instances.
030 *
031 * @author ogrisel
032 * @since 5.7
033 */
034public class NumberMarshaller implements JsonMarshaller<Number> {
035
036    @Override
037    public String getType() {
038        return "number";
039    }
040
041    @Override
042    public Class<Number> getJavaType() {
043        return Number.class;
044    }
045
046    @Override
047    public Number read(JsonParser jp) throws IOException {
048        jp.nextToken();
049        jp.nextToken();
050        return jp.readValueAs(Number.class);
051    }
052
053    @Override
054    public void write(JsonGenerator jg, Object value) throws IOException {
055        Number number = (Number) value;
056        if (number instanceof Double || number instanceof Float) {
057            jg.writeNumber(number.doubleValue());
058        } else {
059            jg.writeNumber(number.longValue());
060        }
061    }
062
063}