views:

235

answers:

1

Hi.

I am working in GWT. Currently my requirement is simple. I want a JSON in following format:

{":question" : { ":id":"123", ":question_text":"some text", ":nodes":["123","111"]}}

I need to create an object in GWT code such that when I use jquery's json plugin to parse that object; I should get above listed json. This json needs to be sent to a remote service.

Currently I have tried using Java Hashmaps and Java custom objects modelled for these attributes but they always seem to have metadata in generated JSON and I am just not able to get this format.

It would be great if someone could suggest how I could go about modelling this data object such that I was get a JSON parsed as expected.

Or can I just write a simple custom JSON parser in Javascript? How do I do that?

cheers -Priyank

+2  A: 

Just to throw it out there, there are a few JSON Java libraries that are pretty nice and simple. The two I have most of my experience with are:

The benefit to both (and most other JSON libraries for Java) is that they handle marshalling most native Java object types to sane JSON equivalents -- in other words, they make it easy to add the contents of a variable to a JSON structure, whether the variable's an integer, long, string, boolean, whatever. So with JSON-Lib, you could build your example as such:

int id = 123;
String questionText = "some text";
int[] nodes = new int[] { 123, 111 };

JSONObject question = new JSONObject();
question.put(":id", id);
question.put(":question text", questionText);
question.put(":nodes", nodes);
JSONObject json = new JSONObject();
json.put(":question", question);

String jsonString = json.toString();
delfuego