jsonexception:value< ?java.lang.string类型的xml无法转换为jsonobject

ruoxqz4g  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(365)

我有一个在android中使用httpget从webservice获取数据的方法。
这是我的密码:

protected Void doInBackground(Void... arg0){

            HttpHandler sh = new HttpHandler();

            // making request to url and getting respose
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " +jsonStr);

            if (jsonStr != null){
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);

                    // getting json array node
                    JSONArray shipments = jsonObject.getJSONArray("string");

                    // looping through all shipments
                    for (int i = 0; i < shipments.length(); i++){

                        JSONObject c = shipments.getJSONObject(i);

                        String id = c.getString("ID");
                        String controlnumber = c.getString("ControlNumber");
                        String clientcn = c.getString("clientcn");
                        String chargeableweight = c.getString("ChargeableWeight");

                        // tmp hashmap for single shipmentdetail
                        HashMap<String, String> shipment = new HashMap<>();

                        // adding each child nodeto hashmap
                        shipment.put("id", id);
                        shipment.put("controlnumber", controlnumber);
                        shipment.put("clientcn", clientcn);
                        shipment.put("chargeableweight", chargeableweight);

                        // adding shipment to shipment list
                        shipmentList.add(shipment);
                    }
                }catch (final JSONException e){
                    Log.e(TAG, "Json parsing error: " +e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " +e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }else {
                Log.e(TAG, "Couldn't get Json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
            return null;
        }

public String makeServiceCall(String reqUrl){

        String response = null;

        try {

            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

             //read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        }catch (MalformedURLException e){
            Log.e(TAG, "MalformedException: " +e.getMessage());
        }catch (ProtocolException e){
            Log.e(TAG, "Protocal Exception: " +e.getMessage());
        }catch (IOException e){
            Log.e(TAG, "IOException: " +e.getMessage());
        }catch (Exception e){
            Log.e(TAG, "Exception: " +e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is){

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null){

                sb.append(line).append('\n');
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                is.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

my web service以以下格式返回数据:

Response from url: <?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"ID":144412,"ControlNumber":186620,"clientcn":160054,"ChargeableWeight":1.00,"TotalPieces":1,"SpecialPickup":false,"ReadyDate":null,"CompanyName":"233 / Evergreen","CompanyAddress":"582 Tuna Street","CompanyAddress1":"45288","City":"Terminal Island","State":"CA","ZipCode":"90731","ContactPhone":"","ContactName":"","C_CompanyName":"Mitoy Logistics","C_CompanyAddress":"1140 Alondra blvd","C_CompanyAddress1":"","C_City":"Compton","C_State":"CA","C_ZipCode":"90220","C_ContactPhone":"","C_ContactName":"John ","priority":5,"FreightShipment":false,"FreightDetails":"20 STD CNTR#  SCLU7888484"}]</string>

如何在android中将响应转换为json对象?这正在消磨我宝贵的时间,不能再继续下去了。我被困在这里了。
任何想法或建议请!
提前谢谢。。

wd2eg0qa

wd2eg0qa1#

如评论中所述,将json和xml混合使用并不是一个好主意。
但是,作为一个快速解决办法,你可以尝试 split 接收的字符串使用 [<,>] 作为regex字符串,并查看所需jsonstring的索引,然后使用它。
比如:

...
String[] stringSplit = serverResponseString.split("[<,>]");

//assuming the JSON is at the 4th index of the stringSplit array
String jsonString = stringSplit[4];

注意:对于问题中的给定示例,计算为有效json字符串所需的部分是: [{"ID":144412 ... SCLU7888484"}] 编辑:只要响应格式相对于xml格式保持不变,上述解决方案就可以工作。如果可以更改,更好的解决方案是首先解析xml,获取字符串内容,并将其用作jsonstring。

jfewjypa

jfewjypa2#

您的响应不是json,或者更好,是无效的json。有关json.json语法的更多信息,请参见此处

相关问题