Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

android - org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject

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

my code is,

public class PropertyRequestService  {

static String result;
PropertiesList localProperty = new PropertiesList();
List<PropertiesList> Properties;
List<PropertiesList> PropertiesRS;

public List<PropertiesList>  getAllPropertiesStuff() {

    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "Here Given Webservice URL");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs
                .add(new BasicNameValuePair("string", "value"));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(httppost);

        HttpEntity entity = response.getEntity();
        if (entity != null) {


            InputStream instream = entity.getContent();
           String response1= convertStreamToString(instream);

            // Closing the input stream will trigger connection release
            instream.close();
            //result = EntityUtils.toString(entity);
            Log.i("RESPONSE=", response1);

            JSONObject json = new JSONObject(response1);

            PropertiesRS.add(SplitResult(json));
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    return PropertiesRS;
}

 public static String convertStreamToString(InputStream instream) {

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

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "
");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
}

This is the logcat,

05-21 11:44:27.320: W/System.err(13234): org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
05-21 11:44:27.320: W/System.err(13234):    at org.json.JSON.typeMismatch(JSON.java:107)
05-21 11:44:27.320: W/System.err(13234):    at org.json.JSONObject.<init>(JSONObject.java:158)
05-21 11:44:27.328: W/System.err(13234):    at org.json.JSONObject.<init>(JSONObject.java:171)
05-21 11:44:27.328: W/System.err(13234):    at com.BuildersUpdate.PropertySearchTypes.PropertyRequestService.getAllPropertiesStuff(PropertyRequestService.java:68)

My webservice returns the data in this format,

05-21 11:44:27.320: I/RESPONSE=(13234): <?xml version="1.0" encoding="utf-8"?>
05-21 11:44:27.320: I/RESPONSE=(13234): <string xmlns="http://localhost/">[{"TbbId":0,"PropertyID":1066666,"BuilderID":"9250c666-e76c-4206-8b37-343b2bb11a89","BuilderName":"David Weekley Homes","Notes":"","Address":"1 TBB4307","SchoolDistrict":null,"School":null,"CityID":"Austin","CountyID":"","StateID":"TX","Zip":"78737","Lat":"30.192781000000000","Lng":"-97.984480000000000","Price":391990,"PropertyStatusID":"AV","PropertyStatusDescription":"Available","StageID":"TBB","StageDescription":"To-Be-Built Home","TypeID":1,"TypeDescription":"House","SubdivisionID":3312,"SubdivisionName":"Belterra","FloorPlanNumber":"4307","Remarks":"","OldNew":null,"PropertyInMyListFlag":null,"FreePostingFlag":"F","PropertySubscriptionPlan":null,"PropertySubscriptionPaymentType":null,"BalanceAmount":0,"PropertyLicenseFlag":"N","PlanNumber":null,"SubdivisionFloorPlanID":null,"SubdivisionFloorPlanName":"Newtown","ShowDirections":"Monday-Saturday 10am-6pm
Sunday 12pm-6pm ","DrivingDirections":"From HWY 290, Take 290 West towards Dripping Springs. Belterra is 7 miles past the intersection of 290 and 71 on the left. Turn left onto Belterra Drive. Turn right onto Abbott Drive, our model is on the left.","PropertyClass":"TBB","RemarksId":0,"VerifiedBU":"Y","SubdivisionDescription":null,"Contact1Name":"Rachea McMurray-Pendley","Contact1Phone":"866-933-5539","Contact1PhoneAlt":"","Contact2Name":"Telenna Thompson","Contact2Phone":"512-821-8821","Contact2PhoneAlt":"","Email":"","Beds":4,"Baths":3,"HalfBaths":1,"Living":0,"Dining":0,"OtherRooms":"","Stories":2.0,"Master":"Down","Garage":3.0,"SquareFeet":3320,"LotSize":"","LotDescription":"Enjoy a host of amenities and award-winning homes in Belterra, a premier community in Austin, Texas. Located just minutes from downtown Austin, Belterra offers residents the opportunity to live, work and play in a community that fits their lifestyle. Here, you can enjoy the &amp;ldquo;Exemplary&amp;rdquo; schools of Dripping Springs ISD plus: &amp;nbsp; Resort-style pool with splash pad for the kids Rooster Springs Elementary School on site Recreation center, outdoor pavilion, club house and fitness center Sport court, ball fields and several children's playscapes Over 400 acres dedicated to parks, sports fields and undisturbed green spaces Miles of walking trails to enjoy the great outdoors 70 x 130 homesites that back up to greenbelts with gorgeous hill country views Over 400 acres dedicated to parks, sports fields and undisturbed green space","CommunityTypeID":11,"CommunityTypeDescription":"Standard","LotWidth":0,"LotLength":0,"Acres":0,"Water":"","Sewer":"","DryUtilities":"","Topography":"","Trees":"","VirtualTourURL":"","InternetOption":"","WaterId":0,"SewerId":0,"DryUtilitiesId":0,"TopographyId":0,"TreesId":0,"InternetOptionId":0,"WaterIds":null,"SewerIds":null,"DryUtilitiesIds":null,"TopographyIds":null,"TreesIds":null,"InternetOptionIds":null,"MinimumPrice":0,"MaximumPrice":0,"MinimumPropertySquareFeet":0,"MaximumPropertySquareFeet":0,"MinimumBeds":0,"MaximumBeds":0,"MinimumBaths":0,"MaximumBaths":0,"MinimumHalfBaths":0,"MaximumHalfBaths":0,"MinimumStories":0,"MaximumStories":0,"MinimumGarages":0,"MaximumGarages":0,"IsModel":null,"CustomHomeModelId":0,"BrandName":null,"SchoolDistrictID":0,"SchoolDistrictName":null,"ElementarySchool":null,"MiddleSchool":null,"HighSchool":null,"SchoolComments":"Please visit the school district's website for additional information about attendance boundaries and school activities.","HasHOA":true,"HOA":"","HOAFee":106.25,"HOABillingPeriod":"Quarterly","CommissionPaid":"TBD","BuyerIncentive":"Please call for current incentives.","AgentIncentive":"Please call for current incentives.","PropertyImageID":5775047,"PropertyImage":"PropertyImages/20130316\P1066666__031613163405_2040133366_5775047.jpg","IsModified":false,"StatusID":40,"StatusDescription":"Active","EntryDate":new Date(1350438245980),"ModifyDate":new Date(1363450564963),"AvailableDate":new Date(-59011459200000),"UserIDModifiedBy":"4a2aef16-e7d9-469a-95ad-5c8935cb6bab","UserIDApprovedBy":"0000000

I dont know the why this exception is being raised.

I cannot change the application to send data in json format due to the restriction of client requirements.

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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you are getting JSON response covered by XML tag, you have to write a logic that will give you that JSON data.

/**
 * To fetch JSON Text between XML tags
 * For example: 
 * <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"> JSON Response text </string>
 * @param response
 * @return
 */
public String getJSONString(HttpResponse response) {

    try {
         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = builder.parse(response.getEntity().getContent());
         NodeList nl = doc.getElementsByTagName("string");
         Node n = nl.item(0);
         String str = n.getFirstChild().getNodeValue();
         System.out.println("Node value : " + str);
         return str;
    } catch (ParserConfigurationException e) {
         e.printStackTrace();
    } catch (SAXException e) {
         e.printStackTrace();
    } catch (IllegalStateException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 return null;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...