1

I have this Java class:

class Car {
     int mileage;
     int id;
}

When I tell gson to serialize it, it of course serializes it to:

{
  "mileage": 123,
  "id": 12345678
}

But what if I want to serialize it to:

{
  "mileage": "123",
  "id": "12345678"
}

Assuming changing my members from int to String, is not an option, is there a way to tell gson to serialize those int members as strings to the json file?

speller
  • 1,641
  • 2
  • 20
  • 27
  • 1
    Thank you all, found this answer, that solves this exactly: https://stackoverflow.com/questions/11586299/how-to-prevent-gson-from-converting-a-long-number-a-json-string-to-scientific – speller Jan 08 '18 at 10:03

2 Answers2

3

There are likely many ways to achieve what you desire. I will share two ways.

FIRST - Using Custom Serialization

SECOND - Using JsonAdapter Annotation - More Simple

Using a custom serialization

public static class CarSerializer implements JsonSerializer<Car> {
    public JsonElement serialize(final Car car, final Type type, final JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        result.add("mileage", new JsonPrimitive(Integer.toString(car.getMileage())));
        result.add("id", new JsonPrimitive(Integer.toString(car.getId())));

        return result;
    }
}

To call this, simply adapt your code or use the following code with a constructor

    Car c = new Car(123, 123456789);
    com.google.gson.Gson gson = new 
    GsonBuilder().registerTypeAdapter(Car.class, new CarSerializer())
            .create();
    System.out.println(gson.toJson(c));

The output should be

{"mileage":"123","id":"12345678"}

Full Code for Example 1:

public class SerializationTest {

    public static class Car {
        public int mileage;
        public int id;
    
        public Car(final int mileage, final int id) {
            this.mileage = mileage;
            this.id = id;
        }

        public int getId() {
            return id;
        }

        public void setId(final int id) {
            this.id = id;
        }

        public String getMileage() {
            return mileage;
        }    

        public void setMileage(final String mileage) {
            this.mileage = mileage;
        }

    }    

    public static class CarSerializer implements JsonSerializer<Car> {
        public JsonElement serialize(final Car car, final Type type, final JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        result.add("mileage", new JsonPrimitive(Integer.toString(car.getMileage())));
        result.add("id", new JsonPrimitive(Integer.toString(car.getId())));

        return result;
    }
}

public static void main(final String[] args) {
    Car c = new Car(123, 123456789);
    com.google.gson.Gson gson = new 
    GsonBuilder().registerTypeAdapter(Car.class, new CarSerializer())
            .create();
    System.out.println(gson.toJson(c));
}

}

Using a @JsonAdapter annotation

Use the JsonAdapter Annotation on the Car class

@JsonAdapter(CarAdapter.class)
public class Car {
    public int mileage;
    public int id;
}

Create the Custom Adapter

public  class CarAdapter extends TypeAdapter<Car> {

    @Override
    public void write(JsonWriter writer, Car car) throws IOException {
        writer.beginObject();

        writer.name("mileage").value(car.getMileage());
        writer.name("id").value(car.getId());  
        writer.endObject();
    }

    @Override
    public Car read(JsonReader in) throws IOException {
        // do something you need
        return null;
    }

}

To serialize, using this method, use something like this

Car c = new Car(123, 123456789);
Gson gson = new Gson();    
String result = gson.toJson(c);

Printing result in this case should output

{"mileage":"123","id":"12345678"}
Community
  • 1
  • 1
Thomas Rokicki
  • 572
  • 1
  • 5
  • 16
0

You may try it this way:

new GsonBuilder()
  .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
  .registerTypeAdapter(Integer.class, (JsonSerializer<Integer>)
    (integer, type, jsonSerializationContext) -> new       
      JsonPrimitive(String.valueOf(integer)))
  .excludeFieldsWithoutExposeAnnotation().create();
B--rian
  • 5,578
  • 10
  • 38
  • 89