【问题标题】:JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObjectJSONException:Java.lang.String 类型的值 <?xml 无法转换为 JSONObject
【发布时间】:2017-12-19 13:40:55
【问题描述】:

我有一个方法,我在 android 中使用 http get 从 web 服务中获取数据。

这是我的代码:

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

我的网络服务以这种格式返回数据:

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对象?这正在消耗我宝贵的时间,而不是继续前进。我被困在这里了。

请有任何想法或建议!

提前谢谢..

【问题讨论】:

  • 您只需将 xml 标记从响应的末尾移除。然后解码内部。
  • 在得到响应后我该怎么做才能使用 trim String 方法?
  • 曾经有过将 XML 与 JSON 混合的“绝妙”想法的人应该告诉您,在将有效负载传递给 JSON 解析器之前,您首先需要解析 XML 文档(使用 XPATH 或类似方法)。向这位“互联网时代的英雄”问好。
  • @Timothy Truckle 他是我的客户,我不知道如何解析这种混合,我先尝试了 xml,现在尝试了 json。你能写一个方法让我解析第一个 xml 吗?
  • @Jazib_Prince “他是我的客户” 那么你为什么不做你的工作并建议你的客户使用一种或另一种文档类型,而不是混合使用两者呢?阻力最小的方式总是导致痛苦和痛苦......

标签: java android json web-services


【解决方案1】:

正如 cmets 中所述,混合 JSON 和 XML 并不是一个好主意。

但是,作为一种快速解决方法,您可以尝试使用[&lt;,&gt;] 作为正则表达式字符串来尝试split 接收到的字符串,并查看所需的 JSON 字符串位于哪个索引处,然后使用它。

类似:

...
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 格式保持不变,上述解决方案就可以工作。如果它可以改变,更好的解决方案是parse the XML first,获取字符串内容,并将其用作JSONstring。

【讨论】:

    【解决方案2】:

    您的响应不是 JSON,或者更好的是,是无效的 json。在这里查看更多关于 json 的信息。JSON syntax

    【讨论】:

    • 是的,它的xml和json混合在一起,问题是如何从这个xml和json混合的字符串中取出json?
    猜你喜欢
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多