0

I'm using the JSON library floating around for Blackberry and following this answer in "How to parse the JSON response in Blackberry/J2ME?".

The problem I'm having is that I'm getting an error saying JSONObject has to begin with a "{". My JSON string is wrapped in [ ] , which is something the web service does.

Libraries I've used for Android and iPhone stripped that, so I was wondering what is the best way around this problem? I don't think I can just parse out all [ ] because I think those are used in multidimensional JSON strings.


Edit:

Here's an example:

[{"nid":"1","title":"test","image":"m0.jpg","by":"Presented by","by_name":"Inc.","summary":"..."}, {"nid":"6","title":"A","image":".jp[0.0] g","by":"Presented by","by_name":"Theatre","summary":""}]
Community
  • 1
  • 1
Adam
  • 8,849
  • 16
  • 67
  • 131
  • Give an example of JSON data, but a JSON input starting with `[` is an array, not an object – fge Dec 26 '11 at 22:39
  • please check once http://docs.blackberry.com/en/developers/deliverables/21128/Code_sample_Parse_JSON_data_structure_1319797_11.jsp – Govindarao Kondala Dec 27 '11 at 05:19

2 Answers2

0

If you are not sure about the validity of JSON data then use any JSON Validator, e.g. JSONLint.

And you have some unwanted character in your data, i.e. [, and ] in "image":".jp[0.0] g". I think those data are added by Eclipse while printing on console.

Data provided in example isn't represent a JSONObject, butit is an array. So start with constructing a JSONArray from the data and do the parsing. Below is an example code snippet (with modified data set):

String strJSONData = "[{\"nid\":\"1\",\"title\":\"test\"},{\"nid\":\"6\",\"title\":\"A\"}]";
final String CONS_NID = "nid";
final String CONS_TITLE = "title";
try {
    JSONArray ja = new JSONArray(strJSONData);
    if (ja != null) {
        JSONObject arrObj;
        for (int i = 0; i < ja.length(); i++) {
        arrObj = (JSONObject) ja.get(i);
        if (arrObj.has(CONS_NID)) {
                System.out.println("ID: " + arrObj.getString(CONS_NID));
        }
        if (arrObj.has(CONS_TITLE)) {
            System.out.println("Title: " + arrObj.getString(CONS_TITLE));
        }
        }
        arrObj = null;
    }
    ja = null;
} catch (Exception exc) {
}
strJSONData = null;
Rupak
  • 3,674
  • 15
  • 23
0

If you know it is starting and ending with '[' and ']', then you can just check that, and take the substring in between and hand it to the parser.

String myJsonString = ...;
if(myJsonString.charAt(0) == '[' && myJsonString.charAt(myJsonString.length() - 1) == ']') {
    realJsonParse(myJsonString.substring(1, myJsonString.length() - 1);
}
Michael Donohue
  • 11,776
  • 5
  • 31
  • 44