How to prevent Gson from expressing integers as floats

后端 未结 6 2017
一生所求
一生所求 2020-11-27 03:23

Gson has some odd behavior when I try to convert a string to json. The code below transforms string draft into json responses. Is there a way to prevent gson from adding the

6条回答
  •  温柔的废话
    2020-11-27 03:33

    This work for me.

    Step 1: Copy the ObjectTypeAdapter in gson into the project, keeping the path the same as in gson Like this

    com
      - xxx
        - xxx
    com
      - google
        - gson
          - internal
            - bind
              ObjectTypeAdapter
    

    Step 2: Modify ObjectTypeAdapter

    case NUMBER:
      return in.nextDouble();
    

    Modified to

    case NUMBER:
      String number = in.nextString();
      try {
        return Long.valueOf(number);
      } catch (NumberFormatException e) {
        return Double.valueOf(number);
      }
    

    OK. Gson will prioritizes the ObjectTypeAdapter in the project.

提交回复
热议问题