3

I am uploading an object to a server and the "value" field accepts Strings, Ints, and Boolean values.

Here is the model with the clearly failed application of @SeralizedName.

public class InspectionFormItems {

@SerializedName("id")
private Integer id;

@SerializedName("type")
private String type;

@SerializedName("value")
private String stringValue;

@SerializedName("value")
private boolean boolValue;

@SerializedName("value")
private int intValue;

@SerializedName("name")
private String name;

@SerializedName("children")
ArrayList<ArrayList<InspectionFormItems>> subitems;
}

Most of the stackoverflow results I found were for Serializing entire objects, or De-Serializing. Some of my ideas were..

  • Is it possible to remove @SerializedName from the three value fields and only serialize the value that isn't null?
  • Can I build some sort of optional data-type-object in java that is set based on the data type that has a value?

This object is part of a larger object and the subitems object has a fair bit of depth to it it just as a note. I expect this to be a duplicate of some question, I just have been unable to find it so far.

Edit:

This is the closest question I have found though I would rather not custom serialize the entire object the way this person has as there could be 40-100 of these objects in this outgoing json gson-same-field-name-different-types-serialize

I've also discovered I can not dynamically set the @SerializedValue attribute is-it-possible-to-pass-method-parameter-to-annotation-on-a-method?

3rd Edit: Let me know if I should delete a bunch of this excess. I am trying to implement this method - inner serialization - this answer though is old an tough to make work right now.

C. Skjerdal
  • 2,750
  • 3
  • 25
  • 50
  • 4
    Did you try `private Object value;`? – Andreas Nov 24 '19 at 05:00
  • Wow yeah that worked, this looks like some basic java programming concept that I have over looked. I can delete this question, or if you want to post this as an answer and I'll clean up my question and mark yours correct. Thanks! – C. Skjerdal Nov 24 '19 at 16:04
  • 1
    If you think it would be helpful to others to see an answer to this question, you can self-answer it, otherwise just delete it. You might get the [Self-Learner](https://stackoverflow.com/help/badges/14/self-learner) badge if you self-answer and others find it useful. – Andreas Nov 24 '19 at 21:56

1 Answers1

3

Thanks to Andreas for their answer.

Using Object, I was able to avoid pre-defining the variable.

@SerializedName("value")
private Object value;

This allowed me to pass both String, Integer, or boolean to the same value field.

C. Skjerdal
  • 2,750
  • 3
  • 25
  • 50