How to remove special characters from JSON stream, so that I can use gson API to convert JSON objects to JAVA objects?

前端 未结 3 721
生来不讨喜
生来不讨喜 2021-01-19 03:43

I am trying to use Google gson API to serialize JSON objects to java objects. I need to remove special characters from this stream for the serialization. How do I achieve t

3条回答
  •  旧巷少年郎
    2021-01-19 04:24

    As I understand it, your object's JSON representation contains a value such as "0%" (which is officially a String from JSON's point of view). This is certainly valid JSON, and GSON should accept it...if you were deserializing it to something that was designed to contain a String.

    My guess is that you actually want the "0" to be deserialized into a numeric type. In this case, you can't rely on GSON to do what you want automatically, and you will need to write a custom deserializer.

    The example in the link above shows how one might do this for a DateTime object:

    private class DateTimeDeserializer implements JsonDeserializer {
      public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
          throws JsonParseException {
        return new DateTime(json.getAsJsonPrimitive().getAsString());
      }
    }
    

    In your case, you will still need to do a getAsString(), but instead of passing it to the DateTime constructor, you would want to apply your own transformations (strip the "%", parse the numeric part, etc) and return the appropriate data type that corresponds to your object.

提交回复
热议问题