在Android中将Json String转换为List

时间:2017-04-05 20:59:26

标签: java android json

    strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}

 JSONObject json = new JSONObject(strResponse);

            // get LL json object
 String json_LL = json.getJSONObject("GetCitiesResult").toString(); 

现在我想将json字符串转换为andriod中的List

5 个答案:

答案 0 :(得分:6)

请确保您的响应字符串格式正确,如果是,请尝试以下操作:

try {
    ArrayList<String> list = new ArrayList<String>();
    JSONObject json = new JSONObject(strResponse);
    JSONArray array = json.getJSONArray("GetCitiesResult");
    for (int i = 0; i < array.length(); i++) {
        list.add(array.getString(i));
    }
} catch (Exception e) {
    e.printStackTrace();
}

答案 1 :(得分:2)

只需使用Gson库,您就可以将json响应转换为pojo类。

使用以下链接复制json字符串以创建pojo结构:http://www.jsonschema2pojo.org/

Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);

它将为该对象中的GetCitiesResult对象提供一个响应列表,如

public List<String> getGetCitiesResult() {
    return getCitiesResult;
}

仅拨打citiesResult.getGetCitiesResult();,它会提供城市列表。

您也可以使用此库com.squareup.retrofit2:converter-gson:2.1.0

答案 2 :(得分:0)

这段代码完成了这个伎俩

List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
                              .stream()
                              .map(o -> (String) o)
                              .collect(Collectors.toList());
list3.forEach(System.out::println);

并打印:

1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123

答案 3 :(得分:0)

下面是代码:

 private void parse(String response) {
    try {

        List<String> stringList = new ArrayList<>();
        JSONObject jsonObject = new JSONObject(response);
        JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");

        for (int i=0; i <jsonArray.length(); i++){
            stringList.add(jsonArray.getString(i));
        }
Log.d ("asd", "--------"+ stringList);


    } catch (Exception e) {
        e.printStackTrace();
    }
}

希望它会有所帮助。

输出是打印列表:

 --------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]

答案 4 :(得分:-1)

好的,你必须先了解 JSON

Json对象是{// some attribute}

Json数组是[// some attribute]

现在你有

{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}

那表示您拥有JSON数组 GetCitiesResult

有String数组

现在试试这个

 JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult")); 
                        for (int i = 0; i <DoctorData.length(); i++) {// what to do here}

其中数据是您的字符串