Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java class that can represent an arbitrary Javascript object?

I'm looking for a java class that is able to represent a dynamic javascript object. This is so that I can move from and to Json while providing easy access to the data. I would like this class to have access methods similar to what you would expect in a javascript object.

Preferences p = new Preferences(...);

p.getString("a");
p.getInteger("a");
p.getObject("a");

All of the above would cast to the appropriate type or return null. Now the key part should be able to be something like this:

p.getString("a.b.c");
p.getString("a[0].b.d[1]");

And so on. Is there something already done that handles like this?

like image 624
Ricardo Marimon Avatar asked Jul 16 '26 12:07

Ricardo Marimon


2 Answers

If you're trying to translate between JSON and Java, Gson is a good bet.

like image 127
Jonathon Faust Avatar answered Jul 19 '26 02:07

Jonathon Faust


You can use HashMaps.. JavaScript object are just a little more than that..

If you need the extra methods for casting etc, you can write your own class JsObject or similarly named, which wraps a HashMap and provides those methods.

If all you want is to serialize deserialize between JSON and Java object try Jackson.

like image 40
Goran Jovic Avatar answered Jul 19 '26 02:07

Goran Jovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!