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

com.weaverplatform.protocol.model.AttributeValue Maven / Gradle / Ivy

There is a newer version: 3.27.0
Show newest version
package com.weaverplatform.protocol.model;

import com.google.gson.*;
import com.weaverplatform.protocol.WeaverError;

import java.lang.reflect.Type;

public class AttributeValue {

  private String stringValue;
  private Boolean booleanValue;
  private Double doubleValue;

  private PrimitiveDataType type;

  public AttributeValue(String value) {
    stringValue = value;
    type = PrimitiveDataType.STRING;
  }

  public AttributeValue(boolean value) {
    booleanValue = value;
    type = PrimitiveDataType.BOOLEAN;
  }

  public AttributeValue(double value) {
    doubleValue = value;
    type = PrimitiveDataType.DOUBLE;
  }

  public PrimitiveDataType getType() {
    return type;
  }

  public String asString() {
    return stringValue;
  }

  public Boolean asBoolean() {
    return booleanValue;
  }

  public Double asDouble() {
    return doubleValue;
  }

  public JsonPrimitive getValue() {
    switch(type) {
      case STRING:
        return new JsonPrimitive(stringValue);
      case BOOLEAN:
        return new JsonPrimitive(booleanValue);
      case DOUBLE:
        return new JsonPrimitive(doubleValue);
      default:
        return null;
    }
  }

  public static class AttributeValueSerializer implements JsonSerializer {
    @Override
    public JsonElement serialize(final AttributeValue attributeValue, final Type type, final JsonSerializationContext context) {
      return attributeValue.getValue();
    }
  }
  public static class AttributeValueDeserializer implements JsonDeserializer {
    @Override
    public AttributeValue deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
      JsonPrimitive value = jsonElement.getAsJsonPrimitive();
      if(value.isNumber()) {
        return new AttributeValue(value.getAsNumber().doubleValue());
      } else if(value.isString()) {
        return new AttributeValue(value.getAsString());
      } else if(value.isBoolean()) {
        return new AttributeValue(value.getAsBoolean());
      } else {
        throw new WeaverError(-1, "Unable to parse value not a number, string, or boolean: " + jsonElement.getAsString());
      }
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy