Wednesday, March 12, 2025

Re: JSON.stringfy() doesn't preserve propery names

Thank you! Very helpful!

On Monday, March 10, 2025 at 9:04:41 AM UTC-7 Colin Alworth wrote:
Java field naming rules don't mesh well with user expectations for how JSON.stringify and friends work - for example it is totally legal for a Java subclass to hide a superclass's fields if not private, and if they are private, a subclass and superclass can have the same field name with no hiding at all. To compile these possible states to JS, some other naming has to be used to ensure consistency. This wouldn't so much be "disabling obfuscation", but "no longer guaranteeing correctness".

Roughly two options are available to you:
 * Use a tool like AutoBeans or domino-jackson so that JSON can be created from your Java types, in a way that would be familiar to a Java developer
 * Write your Java like a JS developer would, but annotate with JsInterop to indicate that you plan to always follow JS naming rules (only one constructor ever, no overloaded methods, etc)

If you're writing something quick and simple and never plan on it growing to more than a few properties, I'd lean towards jsinterop - just slap "@JsProperty" on the fields in question (non-long primitives, Boolean or Double boxed primitives, Strings, arrays, and other annotated types, never java collections etc) and call it good. If it may grow or you like your Java to make sense in Java, give domino-jackson a look to use most of the Jackson annotations and generate json marshalling code.

On Monday, March 10, 2025 at 10:52:58 AM UTC-5 anb...@gmail.com wrote:
I'm trying to serialize an object using JSON.stringify(), however since the GWT complier shortens/obfuscates the property names, the resulting JSON has propery names like "a" and "b" instead of the original names, which means that the JSON can't be deserialized by the server because the property names don't match what it expects.

I've tried turning PRETTY style on for the GWT complier, but even then it seems to still change some property names.

Is there any way to tell the GWT compiler to exempt certain classes from obfuscation? Or some easy alternative way to serialize/deserialize JSON? I don't want to have to write a serializer code separately for each class.

--
You received this message because you are subscribed to the Google Groups "GWT Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-web-toolkit+unsubscribe@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/google-web-toolkit/da451391-918c-48a1-8b0c-a07654ec7cfcn%40googlegroups.com.

No comments:

Post a Comment