001/*
002 * Copyright (C) 2014 Square, Inc.
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 *    https://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 */
016package io.avaje.jsonb;
017
018import io.avaje.jsonb.spi.ViewBuilderAware;
019
020import java.lang.reflect.Type;
021
022/**
023 * The core API for serialization to and from json.
024 */
025public abstract class JsonAdapter<T> {
026
027  /**
028   * Write the value to the writer.
029   */
030  public abstract void toJson(JsonWriter writer, T value);
031
032  /**
033   * Read the type from the reader.
034   */
035  public abstract T fromJson(JsonReader reader);
036
037  /**
038   * Return a null safe version of this adapter.
039   */
040  public final JsonAdapter<T> nullSafe() {
041    if (this instanceof NullSafeAdapter) {
042      return this;
043    }
044    return new NullSafeAdapter<>(this);
045  }
046
047  /**
048   * Return true if this adapter represents a json object or json array of objects that supports json views.
049   */
050  public boolean isViewBuilderAware() {
051    return false;
052  }
053
054  /**
055   * Return the ViewBuilder.Aware for this adapter.
056   */
057  public ViewBuilderAware viewBuild() {
058    throw new IllegalStateException("This adapter is not ViewBuilderAware");
059  }
060
061  /**
062   * Factory for creating a JsonAdapter.
063   */
064  public interface Factory {
065
066    /**
067     * Create and return a JsonAdapter given the type and annotations or return null.
068     * <p>
069     * Returning null means that the adapter could be created by another factory.
070     */
071    JsonAdapter<?> create(Type type, Jsonb jsonb);
072  }
073}