All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.gesellix.docker.json.NumberToBigDecimalJsonAdapter Maven / Gradle / Ivy

There is a newer version: 2024-09-15T20-35-00
Show newest version
package de.gesellix.docker.json;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonReader;
import com.squareup.moshi.JsonWriter;

import java.io.IOException;
import java.math.BigDecimal;

public class NumberToBigDecimalJsonAdapter extends JsonAdapter {

  private final JsonAdapter delegate;

  public NumberToBigDecimalJsonAdapter(JsonAdapter delegate) {
    this.delegate = delegate;
  }

  @Override
  public Object fromJson(JsonReader reader) throws IOException {
    if (reader.peek().equals(JsonReader.Token.NUMBER)) {
      // allows Integer or Long values instead of strictly using Double as value type.
      return new BigDecimal(reader.nextString());
    }
    else {
      return delegate.fromJson(reader);
    }
  }

  @Override
  public void toJson(JsonWriter writer, Object value) throws IOException {
    if (value instanceof Number) {
      writer.jsonValue(value);
    }
    else {
      delegate.toJson(writer, value);
    }
  }
}