How can I convert JSON to a HashMap using Gson?

前端 未结 16 2353
臣服心动
臣服心动 2020-11-22 05:14

I\'m requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn\'t hard at all but the other way seems to

16条回答
  •  孤街浪徒
    2020-11-22 05:53

    This is more of addendum to Kevin Dolan's answer than a complete answer, but I was having trouble extracting the type from the Number. This is my solution:

    private Object handlePrimitive(JsonPrimitive json) {
      if(json.isBoolean()) {
        return json.getAsBoolean();
      } else if(json.isString())
        return json.getAsString();
      }
    
      Number num = element.getAsNumber();
    
      if(num instanceof Integer){
        map.put(fieldName, num.intValue());
      } else if(num instanceof Long){
        map.put(fieldName, num.longValue());
      } else if(num instanceof Float){
        map.put(fieldName, num.floatValue());
      } else {    // Double
         map.put(fieldName, num.doubleValue());
      }
    }
    

提交回复
热议问题