Ricardo Marimon
Ricardo Marimon

Reputation: 10687

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?

Upvotes: 3

Views: 123

Answers (2)

Goran Jovic
Goran Jovic

Reputation: 9508

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.

Upvotes: 1

Jonathon Faust
Jonathon Faust

Reputation: 12543

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

Upvotes: 3

Related Questions