0

Is there a better way to handle a field whose value could be different types in jsonschema2pojo rather than having that field generated as java.lang.Object (this is all caused by legacy data that can't be migrated)

For instance, if I have these JSON:

  • "foo" is String
{
  "foo": "bar"
}
  • "foo" is Array
{
  "foo": ["bar", "baz"]
}

I've tried declaring "type" as either a "string" or "array" in hopes the deserialization would somehow be smart enough to transform the value or force cast to either one (didn't work):

{
  "type":"object",
  "properties": {
    "foo": {
      "type": "string"
    }
  }
}
{
  "type":"object",
  "properties": {
    "foo": {
      "type": "array"
    }
  }
}
{
  "type": "object",
  "properties": {
    "foo": {
      "existingJavaType": "java.util.List<String>"
    }
  }
}

How would you recommend I handle this situation? Do I have no choice but to declare "foo" as an Object.

{
  "type":"object",
  "properties": {
    "foo": {
      
    }
  }
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"foo"
})
@Generated("jsonschema2pojo")
public class Example {

@JsonProperty("foo")
public Object foo;

}

I know I could define a second class that handle the logic for casting Object but I'd like to avoid that if possible. Such as:

public class Test extends Example {

  @Override
  public List<String> getFoo(){
   // if this.foo instanceof string return List<String>
   // else return this.foo
  }
}
Paul
  • 521
  • 1
  • 5
  • 14

1 Answers1

-1

You should use Object type and use instanceOf keyword for checking the datatype of the object, once known the type you can use it accordingly. Check the example below:

public void set(final String key, final Object value) {
    final SharedPreferences.Editor editor = sPreferences.edit();
    if (value instanceof String) {
        editor.putString(key, (String) value);
        editor.commit();
    } else if (value instanceof Float) {
        final Float objFloat = (Float) value;
        editor.putFloat(key, objFloat.floatValue());
        editor.commit();
    } else if (value instanceof Long) {
        final Long objFloat = (Long) value;
        editor.putLong(key, objFloat.longValue());
        editor.commit();
    } else if (value instanceof Integer) {
        final Integer objFloat = (Integer) value;
        editor.putInt(key, objFloat.intValue());
        editor.commit();
    } else if (value instanceof Boolean) {
        final Boolean objFloat = (Boolean) value;
        editor.putBoolean(key, objFloat.booleanValue());
        editor.commit();
    }else if (value instanceof Double) {
        editor.putLong(key, Double.doubleToRawLongBits((Double)value));
        editor.commit();
    }
}