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 this?
This is the JSON object I get from the request:
{"color":"Arctic White","imageUrl":"http://www.xyz.com/images/z/1/7/8/8/2/1/1788212-p-DETAILED.jpg","styleId":"1788212","originalPrice":"$64.95","price":"$64.95","productUrl":"http://www.xyz.com/product/7515478/color/51609","percentOff":"0%"}
However, when I try to use Google's gson API to deserialize it to JAVA object- it needs JSON object without any special characters and hence it throws an exception when it encounters '$' and '%'. How can I get rid of these characters without affecting rest of the json object i.e. json result obtained as a string.
It works perfectly as expected. There is no need to remove these special characters from JSON stream to convert it into Java object.
Please have a look at below sample code:
output: (I have deleted URLs from the output due to constrain of StackOverflow site)
You can try with JsonDeserializer to deserializer it as per your need.
I have already posted a sample code on it. Find it HERE
EDIT
Here is the sample code using
JsonDeserializer
.Sample code :
The easiest way would be to turn the stream into a string, use a regex or something to replace the undesired characters, then invoke gson to convert the corrected string into the Java object you want.
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:
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.