问题描述
我有一个方法,从我从web服务在Android中使用HTTP POST获取数据。
I have a method from which I am fetching the data from webservice using http post in android.
我的code是,
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 + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
这是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)
我的web服务返回的数据格式,
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\nSunday 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 &ldquo;Exemplary&rdquo; schools of Dripping Springs ISD plus: &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.
我不能送JSON格式数据的应用程序更改由于客户要求的限制。
I cannot change the application to send data in json format due to the restriction of client requirements.
如何转换在Android中,以JSON对象的反应如何?这是吃了我宝贵的时间,而不是进一步进行。我在这里停留。
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!
在此先感谢。
推荐答案
当你得到JSON响应覆盖XML标签,你必须写一个逻辑,这将使你的JSON数据。
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;
}
这篇关于org.json.JSONException:值小于,java.lang.String类型的XML无法转换为的JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!