【问题标题】:How to convert a string to JSONArray如何将字符串转换为 JSONArray
【发布时间】:2017-03-14 12:05:51
【问题描述】:

我正在点击一个 api 并得到一个字符串响应。响应是这样的

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

我想将此字符串转换为以下类型的 json 数组

[{"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"}]]

谁能帮忙

【问题讨论】:

  • 我不知道如何解析字符串并将字符串的每个元素分配给我的 json 数组中正确的键值对。
  • 我想这就是答案。 stackoverflow.com/questions/15609306/…
  • 我假设您只是使用普通的org.json API,对吧?
  • @Joffrey 是的,我正在使用 org.json api
  • 如果您获得一个国家/地区的多个时区,您的输入格式是什么?看起来您只有一个元素,但您正在寻找每个国家/地区的一组时区。

标签: java json api jsonobject


【解决方案1】:

您可以选择首先从字符串中创建一个 JSONArray,然后从该数组中读取 3 个 3 个元素以创建输出:

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;
}

如果输入不匹配,您可以添加一些错误处理以优雅地失败,甚至尽最大努力恢复。

【讨论】:

    【解决方案2】:

    查看您的String 回复,我创建了一个正则表达式,它将根据您的回复创建四个组。

    DEMO

    假设您的输出总是以四个为一组(即 id、name 和 timezones_id、timezones_name),这个正则表达式将从您提供的输入字符串中提取 4 个组:

    正则表达式:

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

    匹配项

    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`
    

     

    现在,一旦您提取了这 4 个组,您可以简单地在 ArrayListList 中适当地添加并从这些列表中创建 JSONArray

    以下程序通过输入和输出一目了然。

    输入

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

    输出

    [{"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"}]
    

    格式化输出

    [{
    
            "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"
            }
        }
    ]
    

    代码

    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());
        }
    }
    

    【讨论】:

    • 我首先想到了这一点,但它有点矫枉过正,而且改变起来也不是很健壮。我们可以使用org.json 解析的强大功能,而我的解决方案不会遇到太多麻烦,而且它与这种异构输入一样强大。
    猜你喜欢
    • 2012-04-28
    • 2015-02-16
    • 2023-03-21
    • 1970-01-01
    • 2013-03-30
    • 2011-09-21
    • 2013-05-08
    • 1970-01-01
    • 2017-06-04
    相关资源
    最近更新 更多