1

I wrote code that takes a string that holds a JSON data. I'm sorting my JSON object array by ID. When I'm using my method I get this exception: "org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]".

What am I missing here and how to solve it?

private static void ResortJsonByUseCaseID( String jsonArrStr )
{
    JSONArray jsonArr = new JSONArray(jsonArrStr);
    JSONArray sortedJsonArray = new JSONArray();

    List<JSONObject> jsonValues = new ArrayList<JSONObject>();
    for (int i = 0; i < jsonArr.length(); i++) {
        jsonValues.add(jsonArr.getJSONObject(i));
    }

    java.util.Collections.sort( jsonValues, new java.util.Comparator<JSONObject>() {
        private static final String KEY_NAME = "useCaseId";

        @Override
        public int compare(JSONObject a, JSONObject b) {
            String valA = new String();
            String valB = new String();

            try {
                valA = (String) a.get(KEY_NAME);
                valB = (String) b.get(KEY_NAME);
            }
            catch (JSONException e) {
                //do something

                int tal = 9;
            }

            return valA.compareTo(valB);

        }
    });

    for (int i = 0; i < jsonArr.length(); i++) {
        sortedJsonArray.put(jsonValues.get(i));
    }

    jsonArrStr = sortedJsonArray.toString();

}
1
  • Can you add the JSON-data you're trying to sort as well? Commented Oct 15, 2018 at 7:20

1 Answer 1

1

The code you are describing will only work on a json that looks something like this:

[
  { "useCaseId" : "4", ... },
  { "useCaseId" : "1", ... },
  { "useCaseId" : "a", ... },  
  ...
]

As you can see, the string begins with a [ character, like the exception demanded.

Since "most" jsons begin with { I'm guessing that your json structure is different, and then you'll be required to adjust your code accordingly. For example, if your json array is embedded in an object like "most" jsons are:

{
  "useCases" : [
                 { "useCaseId" : "4", ... },
                 { "useCaseId" : "1", ... },
                 { "useCaseId" : "a", ... },  
                 ...
               ]
}

then you would have to create a JSONObject obj = new JSONObject(jsonArrStr) and then get the JSONArray by calling (JSONArray)obj.get("useCases").

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

2 Comments

And how to make obj to have the key "useCases"?
You gotta show us you json data. Any answer I give you without it is guesswork.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.