views:

243

answers:

2

I have a question about type casting. I have the following JSON String:

{"server":"clients","method":"whoIs","arguments":["hello"]}

I am parsing it to the following Map<String, Object>.

{arguments=[hello], method=whoIs, server=clients}

It is now possible to do the following:

request.get("arguments");

This works fine. But I need to get the array that is stored in the arguments. How can I accomplish this? I tried (for example) the following:

System.out.println(request.get("arguments")[0]);

But of course this didn't work..

How would this be possible?

A: 

Maybe

 System.out.println( ((Object[]) request.get("arguments")) [0]);

? You could also try casting this to a String[].

Anyway, there are more civilized ways of parsing JSON, such as http://code.google.com/p/google-gson/.

mindas
yes i tried almost all json parsers. The problem with google-gson is that it requires classes. I think this is bad practice because for almost every type of request i can expect i need to create a class.
nope that doesn't work. But maybe i am wrong about gson...
If you don't have classes, you still need to write code to handle the hierarchy inside JSON. ...and classes were invented just exactly for the same purpose. You could also get the best of both worlds by by writing your own (de)serializers.Anyway, it is hard for me to comment without knowing much of your project details.
mindas
Ah yes of course i understand. Well i am building a content Management System that will have an Enterprise Service Bus architecture. This means that the system will have a lot of small servers who will each have their own function. (for example an pictures server for images and a rights server for right policies etc .). The requests between the servers are based on the following principle: {server:images, method:getPicture(1)}. I already build the system in ruby but for performance i am rebuilding it in java.
And because java doesn't have an eval() method i changed the json requests to: {server:images, method:getPicture, arguments:[1]}
Well, eval() is only needed if you want to execute Javascript, not for parsing JSON. So your change takes content closer to being JSON. :)Just need to add double-quotes in there and you are done.
StaxMan
A: 

Most likely, value is a java.util.List. So you would access it like:

System.out.println(((List<?>) request.get("arguments")).get(0));

But for more convenient access, perhaps have a look at Jackson, and specifically its Tree Model:

JsonNode root = new ObjectMapper().readTree(source);
System.out.println(root.get("arguments").get(0));

Jackson can of course bind to a regular Map too, which would be done like:

Map<?,?> map = new ObjectMapper().readValue(source, Map.class);

But accessing Maps is a bit less convenient due to casts, and inability to gracefully handle nulls.

StaxMan