How to represent an integer in hexadecimal using Gson?

I have a list of objects, say:

List<Timestamp> 

Each Timestamp object includes other objects, in particular, it has a Tag object.

 class Timestamp { String time; ... Tag tag; ... } 

Now each Tag object is identified by an identifier of type Integer.

 class Tag { Integer id; ... } 

For several reasons, I have to write a JSON representation of the entire list of timestamps in a file using the Gson library. In some cases, I need a decimal representation of the identifier of each tag, while in other cases I need identifiers in hexadecimal format.

How can I β€œswitch” between two formats? Consider using the following command to write the entire list of Timestamp objects:

 ps.println(gson.toJson(timestamps)); 

and I cannot add other fields / types / objects to the Tag class because the JSON representation will be different.

+4
source share
2 answers

I think this is the answer:

  • write your own gson serializer for the Tag class.
  • Add a flag variable to the tag, which indicates when to display the identifier in hexadecimal format and when to display the identifier in decimal format.
  • Create a toString () method in the Tag class that pays attention to the added flag.

Custom Serializer (variant from gson doc example)

 private class TagSerializer implements JsonSerializer<Tag> { public JsonElement serialize(Tag src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } } 

Register your own serializer

 GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(Tag.class, new TagSerializer()); 

Tag Updates

 boolean displayIdInHex = false; public void setDisplayIdInDecimal() { displayIdInHex = false; } public void setDisplayIdInHex() { displayIdInHex = true; } public String toString() { ... stuff ... if (displayIdInHex) { ... output id in hex. } else { ... output id in decimal. } } 

Updates TimeStamp public void setDisplayIdInDecimal () {tag.setDisplayIdInDecimal (); }

 public void setDisplayIdInHex() { tag.setDisplayIdInHex(); } 
+1
source

Integer itself has no format, it's just a number.
If you want to have it in hexadecimal format, you should use String instead of Integer .

+1
source

All Articles