Wednesday, September 20, 2017

Re: elemental.json confusion/error



On Wednesday, September 20, 2017 at 12:49:21 PM UTC+2, max.d...@corussoft.de wrote:
Hi there

I recently started using elemental.json. But I recently stumbled upon strange (expected?) behaviour. Is there any good documentation? The javadoc is quiet lacking, at least in this regard. So, what am I confused about?

My first and main advice would be: don't use Elemental.
If you need to parse JSON with a known structure, use JsInterop to describe that structure (as @JsType(isNative=true, namespace=JsPackage.GLOBAL, name="*"), or name="Object" if you can't use name="*"), and then either com.google.gwt.core.client.JsonUtils.<JavaScriptObject>safeEval() with a cast to your JsInterop interface/class, or JsInterop to call JSON.parse() (as @JsMethod(namespace="JSON", name="parse") static native <T> T parseJson(String json)).
If you don't know the structure upfront, then use jsinterop-base's types instead https://javadoc.io/doc/com.google.jsinterop/base/1.0.0-beta-2 (JsPropertyMap mostly, and the Js helper class), and the same method for parsing. You might also want to have a look at elemental2-core: https://javadoc.io/doc/com.google.elemental2/elemental2-core/1.0.0-beta-1 (which BTW defines JSONType.parse(…)), but be careful as Elemental2 is entirely generated, and might change in the future as the generator evolves (also, Elemental 2 might require that you use the HEAD-SNAPSHOT of GWT)

If you need something that can be used in a JVM too, you might be able to use GSON or Jackson to parse into similar structures (possibly define a JsPropertyMap implementation that wraps a LinkedHashMap).

 
First, there is a "getNumber" (and it's equivalents), but those fail with a classcastexception, if you use it on parsed Json. There is no problem if you use it on values that were "put" there. Is that working as intended? 
Second, and I guess this is a bug: If you use get(key).asBoolean() on a recently parsed value, you get the correct value. But if you use it on a value "false" you "put" in, you get true. 

I would be happy if someone could shine some light on this for me :)

These are likely bugs, and they're unlikely to ever be fixed (unless maybe someone provides the patch).

I wrote a small "test" to demonstrate it:

import com.google.gwt.core.shared.GWT;

import elemental.json.JsonObject;
import elemental.json.impl.JsonUtil;

The correct way is Json.instance(), one shouldn't ever use any "impl" 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 post to this group, send email to google-web-toolkit@googlegroups.com.
Visit this group at https://groups.google.com/group/google-web-toolkit.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment