1

I am using jquery.sheet plugin which accepts JSON. The JSON format is:

[
    { //repeats
        metadata: {
            columns: Column_Count,
            rows: Row_Count,
            title: ''
        },
        data: {
            r{Row_Index}: { //repeats
                c{Column_Index}: { //repeats
                    value: '',
                    style: '',
                    width: 0,
                    cl: {Classes used for styling}
                }
            }
        }
    }
]; 

A simple example may be:

[
    { 
        metadata: {
            columns: 1,
            rows: 1,
            title: 'Private Limited'
        },
        data: {
            r0: { 
                c0: { 
                    value: 'A',
                    style: '',
                    width: 0
                }
            }
        }
    }
]

I need to parse this JSON in Java? I know I can use the google's gson library to parse. But I don't know how to do this.

1
  • The bad thing is that rows and column names are not consistent, r0, r1, r2, c0, c1, c2,etc Commented May 24, 2012 at 15:21

1 Answer 1

2

Strictly speaking the sample you are referring to is not a valid JSON, e.g. it lacks "" around field ids as metadata [according to JSON defined in www.json.org][http://json.org/]

For this reason I would recommend that before you pass it to your Java (e.g. servlet) you should stringify this object, e.g. as shown in this answer. This way you are sure that this is a valid JSON. Later use jQuery to send it to servlet. There in your Java code you use the below code to get your json String turned into JSONArray on which you will operate further.

String json = request.getParameter(param);
JSONArray jsonArray = new JSONArray(json);

Then you can iterate over its elements as if it was any other collection.

for (int i = 0; i < jsonArray.length(); i++) {
   JSONObject jsonObject = jsonArray.getJSONObject(i);
   //work with the jsonObject
}

The JSONArray and JSONObject classes are taken from here.

The jar for the library is availalbe here.

You could use gson if you like. Though in this particular case this library is more then enough. I personally use gson if I have a bean object for a corresponding JSON String, otherwise json.org is more than enough.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.