Generically get the value from a JSON object using JsonObject

1,055 views
Skip to first unread message

mathias

unread,
Mar 25, 2015, 6:49:46 PM3/25/15
to ve...@googlegroups.com
I have a generic JSON Object with the key "data". The value for that key can be any vaild JSON value (array, object, string, number..). Example:
{data:["One","Two","Three"]}

Now I need the value of "data" as a string and this must be generic because the value can be of any type. So far I tried this way:
JsonObject jsonObj = (JsonObject) message.body();
String data = jsonObj.getString("data");

But the problem is, that the method getString("data") results in an exception
java.lang.ClassCastException: io.vertx.core.json.JsonArray cannot be cast to java.lang.CharSequence
    at io
.vertx.core.json.JsonObject.getString(JsonObject.java:82)

Any ideas?
 

Jazz

unread,
Mar 25, 2015, 7:37:07 PM3/25/15
to ve...@googlegroups.com

mathias

unread,
Mar 28, 2015, 12:07:34 PM3/28/15
to ve...@googlegroups.com
Your post describes how to generically fill a JsonArray but not how to read it generically. In the meanwhile I discovered tthe following method:

 public Object getValue(String key) {
   
Objects.requireNonNull(key);
   
Object val = map.get(key);
   
if (val instanceof Map) {
      val
= new JsonObject((Map)val);
   
} else if (val instanceof List) {
      val
= new JsonArray((List)val);
   
}
   
return val;
 
}

So JsonObject provides a generic getter already. I just didn't see it in the late evening :-)

Thx!

Reply all
Reply to author
Forward
0 new messages