Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can GSON deserialize in a case-insensitive way

Tags:

In prototyping communication between .NET desktop app and Java server, using REST with JSON posts, I am running into a case-sensitivity issue. The .NET objects have there properties in Pascal Casing (which is conventional for .NET), e.g.: Symbol, EntryValue (etc), while the Java representation of same object uses camel casing, e.g. symbol, entryValue.

The server receives json value as:

{"EntrySize":100,"Symbol":"AMZN"} 

But Gson doesn't deserialize in case-insensitive manner. Is there any way to get Gson to do this?

like image 330
Sam Goldberg Avatar asked Nov 01 '12 04:11

Sam Goldberg


People also ask

Is Gson case sensitive?

The translated name is used as the parameter to the get(String) method of members , and Gson provides no mechanism for this final call to be made case insensitive.

How do you make a JSON Object case insensitive?

You could read the JSONObject into a java string, and call String. toLowerCase on it and store it back into a JSONObject. This will turn the entire case of the string to lower case, so you will have to account for that elsewhere in your logic.

How do I ignore fields in Gson?

ExclusionStrategy strategy = new ExclusionStrategy() { @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } @Override public boolean shouldSkipField(FieldAttributes field) { return field. getAnnotation(Exclude. class) !=

Does Gson ignore extra fields?

3. Deserialize JSON With Extra Unknown Fields to Object. As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.


1 Answers

Use FieldNamingPolicy on a GsonBuilder, to get your Gson object. Yours seems to match UPPER_CAMEL_CASE.

Gson gson = new GsonBuilder()         .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)         .create(); 

For any exceptions, annotate your class field with a @SerializedName annotation.

like image 148
Jeff Bowman Avatar answered Sep 18 '22 03:09

Jeff Bowman