0

I am developing android app where I am getting web-service data as:

"[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"}]"

Now I want to parse this data in json I used replaceAll() function to replace backslashes from the string like this:

 String jsonFormattedString = line.replaceAll("\\\\", "");

But I think this method isnot good to work with because it removes all the backslashes from the string which creates problems like I recieved json node like:

"[{\"ID\":9617,\"Text\":\"1 1\/4\\\" PVC\/GI CLAMPS\"}]"

where the string value for Text contains double quotes within string which creates problem for me. So my question is what is the best way to parse this json data in java.

My full json data returned by webservice is as:

"[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"},{\"ID\":53,\"Text\":\"Kanix City\"},{\"ID\":54,\"Text\":\"KANIX DREAM CITY\"},{\"ID\":59,\"Text\":\"KANIX DREAM CITY -- PHASE II\"},{\"ID\":62,\"Text\":\"KANIX DREAM CITY PHASE I\"},{\"ID\":55,\"Text\":\"Kishor_TEST\"},{\"ID\":63,\"Text\":\"Next Generation Housing\"},{\"ID\":65,\"Text\":\"Nothing Job\"},{\"ID\":56,\"Text\":\"PAVAN_TEST\"},{\"ID\":46,\"Text\":\"PRODUCTION UNITS\"},{\"ID\":1,\"Text\":\"PROJECT-01(TYPE 1)\"},{\"ID\":3,\"Text\":\"PROJECT-02(TYPE 1)\"},{\"ID\":5,\"Text\":\"PROJECT-03(TYPE 1)\"},{\"ID\":6,\"Text\":\"PROJECT-04(TYPE 1)\"},{\"ID\":7,\"Text\":\"PROJECT-05(TYPE 1)\"},{\"ID\":8,\"Text\":\"PROJECT-06(TYPE 1)\"},{\"ID\":2,\"Text\":\"PROJECT-07(TYPE 2)\"},{\"ID\":4,\"Text\":\"PROJECT-08(TYPE 2)\"},{\"ID\":9,\"Text\":\"PROJECT-09(TYPE 3)\"},{\"ID\":10,\"Text\":\"PROJECT-10(TYPE 3)\"},{\"ID\":11,\"Text\":\"PROJECT-11(TYPE 4)\"},{\"ID\":57,\"Text\":\"Reviera Classic\"},{\"ID\":43,\"Text\":\"ROAD PROJECT\"},{\"ID\":41,\"Text\":\"SAMPLE PROJECT 1\"},{\"ID\":42,\"Text\":\"SAMPLE PROJECT 2\"},{\"ID\":52,\"Text\":\"Shailesh Test project@1000\"},{\"ID\":61,\"Text\":\"VISHAL PARADISE\"},{\"ID\":60,\"Text\":\"WTC\"}]"

my full code is like this:

@Override
protected List<CItem> doInBackground(String... params) {
    try {
    String line="";
    String ur = "http://"+ServerDetails.hostServer+"/appservices.svc/Projects?Keyword=" ;

       lstItm=new ArrayList<CItem>() ;


        // Replace it with your own WCF service path
        URL json = new URL(ur);
        URLConnection jc = json.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

         line = reader.readLine();
         Log.d("LINE",line);
           JSONArray array=new JSONArray(line);


        Itm=new CItem( "-1", "Select Project" );
        lstItm.add(Itm);
        for(int i=0; i < array.length(); i++) {
            JSONObject tmpJson=array.getJSONObject(i);


            Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text"));
            lstItm.add(Itm);


        }


        return  lstItm ;






    }
    catch(Exception e)
    {
        Log.d("ERRROR--->",e.getMessage());



    }





    return  lstItm ;

}
1
  • 4
    Use a predefined library like GSON or json-simple Commented May 15, 2015 at 5:54

2 Answers 2

1

@mubu9082 ..you dont need to remove these backslashes... as this json string is shown with backslashes in log or by debugger..

just parse it as usual

public void jsonParser()
{
    ArrayList<> list=new ArrayList<>(); //declare this as global
    String responseString="[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"}]";
    JSONArray array=new JSONArray(responseString);
    String id[]=new String[array.length()];
    String text[]=new String[array.length()];
    for(int i=0;i<array.length();i++)
    {
         JSONObject tmpJson=array.getJSONObject(i);
         id[i]=tmpJson.getString("ID");
         text[i]=tmpJson.getString("TEXT");
         CItem Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text")); lstItm.add(Itm);
         list.add(Itm);
    }
}

do this to get response from server

try {

        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // make GET request to the given URL ...use
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        // receive response as inputStream
        HttpEntity entity = httpResponse.getEntity();

        String response= EntityUtils.toString(entity);
        //pass this response to JSONArray object
        //save response and then flush the entity.
        entity.consumeContent();

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

pass this response to JSONArray object

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

10 Comments

after using your code I got exception like this: 05-15 11:46:52.158 2821-2841/kanix.highrise.com.highrise D/ERRROR--->﹕ Value [{"ID":51,"Text":"!! SAMPLE PROJECT !!"},{"ID":58,"Text":"01 Contracting Test Project"},{"ID":64,"Text":"1212"},{"ID":45,"Text":"CHEMICAL FACTORY PROJECT"}] of type java.lang.String cannot be converted to JSONArray
strange... i've run the same code from this editor to my android-studio..and its working properly...
there is something wrong with responseString...have u tried putting the static value for responseString as i set ?
line = reader.readLine(); JSONArray array=new JSONArray(line); Itm=new CItem( "-1", "Select Project" ); lstItm.add(Itm); for(int i=0; i < array.length(); i++) { JSONObject tmpJson=array.getJSONObject(i); Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text")); lstItm.add(Itm); } return lstItm ; } catch(Exception e) { Log.d("ERRROR--->",e.getMessage()); }
I used above code. please see if I am doing anything wrong
|
0
public InsuranceDO getInsuranceData1(Context context) {

    String urlStr = "http://192.168.2.11:8080/Service/category/sample";
    InsuranceDO insuranceDO = new InsuranceDO();
    HttpURLConnection urlConnection;
    List<InsuranceDO> insList = new ArrayList<InsuranceDO>();
    try {
        String reqVal = "T=421D84EAC8DEB4878CE48C8A0CB870791EB96FE51C7800A8806032A8CE69A4966D87FFA2E139EE6586C1924F9BD070154CB7E8F92985AC6674B0AD37D9F3FC1ED7B2E4C2D01E5525DCE5E6FCDA26AF890633011894AA2B72604CC8B046E4F9C37DE9A61EECD7000325D3EC673E8609AAD753C52B9BC002C014BC18A35AA8AB3636C237088A08EEED72A7C5F2EDE60155E9111A6F74F082C0E4B45D484C00CA5AD5B3560B8A10D47616E48077EBDE490E&UserCode=172278&DBSource=bali";
        URL url = new URL(urlStr);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        OutputStream outputStream = urlConnection.getOutputStream();
        outputStream.write(reqVal.getBytes());
        outputStream.flush();
        int code = urlConnection.getResponseCode();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        StringBuilder result = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        /**
         * To parse json to list data
         */
        JSONArray jsonArray = new JSONArray(result.toString());
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            insuranceDO.setAgeing(jsonObject.getString("xxx"));
            insuranceDO.setInsuredName(jsonObject.getString("yyyy"));
            insuranceDO.setProposalNumber(jsonObject.getString("zzzz"));
            insuranceDO.setReason(jsonObject.getString("aaaa"));
            insList.add(insuranceDO);
        }


    } catch (Exception e) {
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
    Toast.makeText(context, insList.toString(), Toast.LENGTH_LONG).show();
    return insuranceDO;
}

Comments

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.