Skip to content

reading json file integer values as double values in ObjectTypeAdapter #1351

@prem-jason

Description

@prem-jason

Hi,

My sample json is as following:
{
"myevents": [1234, 4567]
}

String path = "src//main//resources/sample.json";
FileReader fileReader = new FileReader(path);
JsonReader jsonReader = new JsonReader(fileReader);
Map<String, ArrayList> map = new HashMap<String, ArrayList>();
Gson gson = new Gson();
Map<String, ArrayList> map1 =gson.fromJson(jsonReader, map.getClass());

System.out.println(map1.get("myevents").toString());

Prints: [1234.0, 5678.0]

Reason:
com.google.gson.internal.bind.ObjectTypeAdapter's read method reads jsons numbers as double values, can you introduce integers, floats or double as case types? instead of treating all numbers as double values. Thanks

@OverRide public Object read(JsonReader in) throws IOException {
JsonToken token = in.peek();
switch (token) {
case BEGIN_ARRAY:
List list = new ArrayList();
in.beginArray();
while (in.hasNext()) {
list.add(read(in));
}
in.endArray();
return list;

case BEGIN_OBJECT:
  Map<String, Object> map = new LinkedTreeMap<String, Object>();
  in.beginObject();
  while (in.hasNext()) {
    map.put(in.nextName(), read(in));
  }
  in.endObject();
  return map;

case STRING:
  return in.nextString();

case NUMBER:
  return in.nextDouble();

case BOOLEAN:
  return in.nextBoolean();

case NULL:
  in.nextNull();
  return null;

default:
  throw new IllegalStateException();
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions