简体   繁体   中英

Convert string of valid JSON to JSON object in Java, so I can index into it

I have this string:

[{"row 0":[{},{},{},{},{},{},{},{}]},{"row 1":[{},{},{},{},{},{},{},{}]},{"row 2":[{},{},{},{},{},{},{},{}]},{"row 3":[{},{},{},{},{},{},{},{}]},{"row 4":[{"column 0":"WhitePawn"},{},{},{},{},{},{},{}]},{"row 5":[{},{},{},{},{},{},{},{}]},{"row 6":[{},{},{},{},{},{},{},{}]},{"row 7":[{},{},{},{},{},{},{},{}]}]

^ it's currently a String, let's call it string .

I'm trying to convert it into JSON like so:

new JSONObject(string);

but it isn't working. How to do this in Java?

Code looks like so:

    private void parseMessageRedrawBoard(String message) {

        Log.d("0000: ", message);

        String trimmed = message.substring(message.indexOf("["));

        Log.d("1111: ", trimmed);

        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(trimmed);
            Log.d("maybe worked...", "~");
        } catch (Exception e) {
            Log.d("dammit: ", e.getMessage());
        }

    }

You are trimming the string and turning it into an invalid JSON.

Your JSON starts with a "[" that indicates it is an array. If it starts with "{" you can assume that is an object.

So, as your JSON is an array, you can parse this exact content you mentioned with:

JSONArray jsonArray = new JSONArray(string);

And access the elements like in a List:

jsonArray.get(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM