0

I have a method from which I am fetching the data from webservice using http get in android.

Here is my code:

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 returns the data in this format:

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>

How to convert the response to json object in android? This is eating away my valuable time and not to proceed further. I am stuck here.

Any idea or suggestions please!

Thanks in advance..

5
  • 1
    You just need to get the xml tags off the ends of your response. Then decode the insides. Commented Jul 14, 2017 at 12:41
  • How can i do that after getting response can I use trim String method for this? Commented Jul 14, 2017 at 12:43
  • 2
    Who ever had that "brilliant" idea of mixing XML with JSON should have told you that you first need to parse the XML document (using XPATH or alike) before passing the payload to a JSON parser. Send my regards to that "hero of the internet age". Commented Jul 14, 2017 at 12:51
  • @Timothy Truckle He's my client and I have no clue to parse this mixing, I tried first xml and now json. Can you please write a method for me to parse firs xml? Commented Jul 14, 2017 at 12:55
  • 1
    @Jazib_Prince "He's my client" so why don't you do your job and suggest your client to use one document type or the other, not mixing both? The way of least resistance always leads to pain and misery... Commented Jul 14, 2017 at 13:30

2 Answers 2

2

As stated in the comments, its not really a good idea to mix JSON and XML.

But, as a quick fix, you can try to split the received string using [<,>] as the regex string, and see at what index is the required JSONstring and then use it.

something like :

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

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

Note : for the given example in the question, the required part that would evaluate to a valid JSON string is : [{"ID":144412 ... SCLU7888484"}]

Edit : The above solution will work as long as the response format remains unchanged with respect to the XML format. In case it can change, the better solution would be to parse the XML first, get the string contents, and use it as the JSONstring.

Sign up to request clarification or add additional context in comments.

Comments

0

Your response is not a JSON , or better , is an invalid json. See here more about json.JSON syntax

1 Comment

Yes its xml mixed with json, the question is how to take json from this xml and json mixed string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.