由" |"分隔的字符串响应到Android JSONObject

时间:2017-10-23 17:51:29

标签: android arrays split

我收到了这样的HTTP GET响应: (是的,我知道这很奇怪)

1,24,https://www.myweb.com/img/BTMz_shave_club.png|10,21,https://www.myweb.com/img/BTMz_coffee_club.png|30,22,https://www.myweb.com/img/BTMz_coffee_club.png|

我需要通过" |"分割字符串。然后拆分","结果如下:

[
  {id: 1, qty: 24, img_uri: https://www.myweb.com/img/BTMz_shave_club.png},
  {id: 10, qty: 21, img_uri: https://www.myweb.com/img/BTMz_coffee_club.png},
  {id: 22, qty: 22, img_uri: https://www.myweb.com/img/BTMz_coffee_club.png}
]

它是一个String响应,但我需要将其转换为JSONArray。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

尝试类似

的内容
private void splitAndMakeJson() {


    JSONArray jsonArray=new JSONArray();
    JSONObject jsonObject=null;
    String mainString="1,24,https://www.myweb.com/img/BTMz_shave_club.png|10,21,https://www.myweb.com/img/BTMz_coffee_club.png|30,22,https://www.myweb.com/img/BTMz_coffee_club.png|";

    String[] mainToken=mainString.split("\\|");

    for(int i=0;i<mainToken.length;i++){
        String subToken[]=mainToken[i].split(",");
        jsonObject=new JSONObject();
        try {
            jsonObject.put("id",subToken[0].getBytes().toString());
            jsonObject.put("qty",subToken[1].getBytes().toString());
            jsonObject.put("img_uri",subToken[2].getBytes().toString());
            jsonArray.put(jsonObject);

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

    }

    Log.e("Json",jsonArray.toString());
}