Siddharth Sinha
Siddharth Sinha

Reputation: 628

How to convert a string to JSONArray

I am hitting an api and getting a string response. The response is something like this

"["VU","Vanuatu",["Pacific/Efate","(GMT+11:00) Efate"],"VN","Vietnam",["Asia/Saigon","(GMT+07:00) Hanoi"]]"

And i want to convert this string into a json array of below type

[{"id":"VN","name":"Vanuatu","timezones":[{"id":Pacific/Efate,"name":"(GMT+11:00) Efate}]},"id":"VN","name":"Vietnam",[{"id":"Asia/Saigon","name":"(GMT+07:00) Hanoi"}]]

Can someone help

Upvotes: 3

Views: 3541

Answers (2)

Joffrey
Joffrey

Reputation: 37710

An option you have is to first create a JSONArray off of the string, and then read elements 3 by 3 from that array to create your output:

public static void main(String[] args) {
    String input = "[\"VU\",\"Vanuatu\",[\"Pacific/Efate\",\"(GMT+11:00) Efate\"],\"VN\",\"Vietnam\",[\"Asia/Saigon\",\"(GMT+07:00) Hanoi\"]]";
    JSONArray inputArray = new JSONArray(input);
    JSONArray outputArray = new JSONArray();
    for (int i = 0; i < inputArray.length(); i += 3) {
        JSONObject obj = readCountry(inputArray, i);
        outputArray.put(obj);
    }
    System.out.println(outputArray);
}

private static JSONObject readCountry(JSONArray array, int index) {
    JSONObject country = new JSONObject();
    country.put("id", array.getString(index));
    country.put("name", array.getString(index + 1));
    country.put("timezones", readTimeZones(array.getJSONArray(index + 2)));
    return country;
}

private static JSONArray readTimeZones(JSONArray array) {
    JSONArray timezones = new JSONArray();
    JSONObject timezone = new JSONObject();
    timezone.put("id", array.getString(0));
    timezone.put("name", array.getString(1));
    timezones.put(timezone);
    return timezones;
}

You may add some error handling to fail gracefully or even recover with best effort if the input doesn't match.

Upvotes: 0

Raman Sahasi
Raman Sahasi

Reputation: 31851

Looking at your String response, I've created a regular expression that will create four groups out of your response.

DEMO

Assuming that your output would come always in groups of four (i.e., id, name and timezones_id, timezones_name), this regular expression, would extract 4 groups out of the input string that you've provided:

Regex:

"([^"]*)",\s*"([^"]*)",\s*\["([^"]*)",\s*"([^"]*)"\]

Matches

Match 1
    Full match  1-56    `"VU", "Vanuatu", ["Pacific/Efate", "(GMT+11:00) Efate"]`
        Group 1.    2-4     `VU`
        Group 2.    8-15    `Vanuatu`
        Group 3.    20-33   `Pacific/Efate`
        Group 4.    37-54   `(GMT+11:00) Efate`
Match 2
    Full match  58-111  `"VN", "Vietnam", ["Asia/Saigon", "(GMT+07:00) Hanoi"]`
        Group 1.    59-61   `VN`
        Group 2.    65-72   `Vietnam`
        Group 3.    77-88   `Asia/Saigon`
        Group 4.    92-109  `(GMT+07:00) Hanoi`

 

Now once you've extracted these 4 groups, You can simply add appropriately in ArrayList and List and create JSONArray out of those lists.

The following program is self-explanatory with the inputs and outputs.

Input

["VU","Vanuatu",["Pacific/Efate","(GMT+11:00) Efate"],"VN","Vietnam",["Asia/Saigon","(GMT+07:00) Hanoi"]]

Output

[{"timezones":{"name":"(GMT+11:00) Efate","id":"Pacific/Efate"},"name":"Vanuatu","id":"VU"},{"timezones":{"name":"(GMT+07:00) Hanoi","id":"Asia/Saigon"},"name":"Vietnam","id":"VN"}]

Formatted Output

[{

        "id" : "VU",
        "name" : "Vanuatu",
        "timezones" : {
            "name" : "(GMT+11:00) Efate",
            "id" : "Pacific/Efate"
        }
    }, {
        "id" : "VN",
        "name" : "Vietnam",
        "timezones" : {
            "name" : "(GMT+07:00) Hanoi",
            "id" : "Asia/Saigon"
        }
    }
]

Code

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;


public class Test
{
    public static void main(String[] args) throws IOException, JSONException {
        String serverResponse = "[\"VU\", \"Vanuatu\", [\"Pacific/Efate\", \"(GMT+11:00) Efate\"], \"VN\", \"Vietnam\", [\"Asia/Saigon\", \"(GMT+07:00) Hanoi\"]]";
        Map<String, Object> prop, innerProp;
        List<Object> arr = new ArrayList<>(), obj;

        String pattern = "\"([^\"]*)\",\\s*\"([^\"]*)\",\\s*\\[\"([^\"]*)\",\\s*\"([^\"]*)\"\\]";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(serverResponse);

        while (m.find()) {
            prop = new HashMap<>();
            prop.put("id", m.group(1));
            prop.put("name", m.group(2));

            innerProp = new HashMap<>();
            innerProp.put("id", m.group(3));
            innerProp.put("name", m.group(4));

            prop.put("timezones", innerProp);
            arr.add(prop);
        }


        JSONArray jsonArray = new JSONArray(arr);
        System.out.println(jsonArray.toString());
    }
}

Upvotes: 1

Related Questions