Creating JsonArray out of list of custom objects

433 views
Skip to first unread message

Oren Shvalb

unread,
Jan 28, 2015, 5:11:04 PM1/28/15
to ve...@googlegroups.com
Hi,

I have the following list:

    List<MyClass> objs;


When I create the following:

    JsonArray arr = new JsonArray(objs);

it raises an exception:

    "Cannot have objects of class class 'MyClass' in JSON"

I have looked into JsonArray code to see why it happens and apparently it accepts only primitive types (Number, String...)

My question: Is there a magical way to overcome this?? jackson annotations or something like that?

Thank you!

Alexander Lehmann

unread,
Jan 28, 2015, 6:11:37 PM1/28/15
to ve...@googlegroups.com
In vert.x 2 that doesn't work, you have to iterate through the list and call your toJSON method if you have one

    JsonArray json=new JsonArray();
   
for(MyClass o: objs) {
      json
.add(o.toJSON());
   
}

Oren Shvalb

unread,
Jan 28, 2015, 7:12:05 PM1/28/15
to ve...@googlegroups.com
Is it any different in Vertx 3.0 ?

Alexander Lehmann

unread,
Jan 29, 2015, 2:19:26 PM1/29/15
to ve...@googlegroups.com
in vert.x 3 I think you can use a class with getters in a JsonObject, in vert.x 2 that isn't implemented apparently

Oren Shvalb

unread,
Jan 29, 2015, 2:44:10 PM1/29/15
to ve...@googlegroups.com
Another reason to switch to v3.0

Thank you

Sent from my iPhone
--
You received this message because you are subscribed to a topic in the Google Groups "vert.x" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/vertx/rbDKRyb7mo8/unsubscribe.
To unsubscribe from this group and all its topics, send an email to vertx+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tim Fox

unread,
Jan 30, 2015, 6:35:36 AM1/30/15
to ve...@googlegroups.com
It's not a Vert.x limitation.

JSON only supports string, number, boolean types. See http://json.org/
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+un...@googlegroups.com.

Alexander Lehmann

unread,
Jan 30, 2015, 6:57:04 AM1/30/15
to ve...@googlegroups.com
yes, I expected the json converter to convert included objects in the list to json as well if that is possible. It looks like this works for objects that are beans in vert.x 3

Alexander Lehmann

unread,
Jan 30, 2015, 6:59:42 AM1/30/15
to ve...@googlegroups.com
discarding the type information I should add, the result is basically

[
 { ... jsonobject for myclass ...},
 { ... jsonobject for myclass ...},
 { ... jsonobject for myclass ...}
]

the same is possible in vert.x 2 but you have to traverse the list explicitly and use a toJson method (that has to be implemented by the class)
Reply all
Reply to author
Forward
0 new messages