替换json字符串的第一次和最后一次出现

时间:2013-05-21 09:23:37

标签: android json string replace

我从webservice获取响应并尝试解析json字符串。

响应字符串是

  [{"TbbId":0,"PropertyID":1066637,"BuilderID":"9250c666-e76c-4206-8b37-343b2bb11a89","BuilderName":"David Weekley Homes","Notes":"","Address":"1 TBB4519","SchoolDistrict":null,"School":null,"CityID":"Fort Mill","CountyID":"","StateID":"SC","Zip":"29708","Lat":"35.037240000000000","Lng":"-80.979742000000000","Price":364990,"PropertyStatusID":"AV","PropertyStatusDescription":"Available","StageID":"TBB","StageDescription":"To-Be-Built Home","TypeID":1,"TypeDescription":"House","SubdivisionID":4121,"SubdivisionName":"Baxter Village","FloorPlanNumber":"4519","Remarks":"","OldNew":null,"PropertyInMyListFlag":null,"FreePostingFlag":"F","PropertySubscriptionPlan":null,"PropertySubscriptionPaymentType":null,"BalanceAmount":0,"PropertyLicenseFlag":"N","PlanNumber":null,"SubdivisionFloorPlanID":null,"SubdivisionFloorPlanName":"Ridgegate","ShowDirections":"Mon-Sat 9:30am-5:30pm; Sun 12:30pm-5:30","DrivingDirections":"Take I-77, Exit 85 - Fort Mill / Highway 160. Take Highway 160 West. Proceed past the Main Baxter Village Entrance. Turn Left into Baxter Village at the next entrance marked by a white fence and stone monument which is Front Street. Take your first right onto Richards Crossing, the David Weekley Model is located on the left at 3439 Richards Crossi","PropertyClass":"TBB","RemarksId":0,"VerifiedBU":"Y","SubdivisionDescription":null,"Contact1Name":"Traci Belk","Contact1Phone":"800-393-9968","Contact1PhoneAlt":"","Contact2Name":"","Contact2Phone":"","Contact2PhoneAlt":"","Email":"homes@dwhomes.com","Beds":4,"Baths":2,"HalfBaths":1,"Living":0,"Dining":0,"OtherRooms":"","Stories":2.0,"Master":"Down","Garage":2.0,"SquareFeet":2474,"LotSize":"","LotDescription":"David Weekley homes Traditional Collection in Baxter Village offers floor plans featuring innovative design and unsurpassed quality. This charming community combines work, play and living, all within the Village. In Baxter Village, you’ll enjoy:  Parks, playgrounds and sports courts Swimming pool and clubhouse Community library and two community centers Full time activities director for events Baxter Town Center with shopping and dining Final Phase of Baxter Village Nearly Sold Out! Love Baxter Village but want to build a more customized home on a larger estate lot? We can help! Learn more about our Build on Your Lot program.","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":0,"HOABillingPeriod":"","CommissionPaid":"TBD","BuyerIncentive":"Please call for current incentives.","AgentIncentive":"Please call for current incentives.","PropertyImageID":5483435,"PropertyImage":"PropertyImages/20130218\\P1066637__021813220800_817965289_5483435.jpg","IsModified":false,"StatusID":40,"StatusDescription":"Active","EntryDate":new Date(1350438233950),"ModifyDate":new Date(1361225162697),"AvailableDate":new Date(-59011459200000),"UserIDModifiedBy":"4a2aef16-e7d9-469a-95ad-5c8935cb6bab","UserIDApprovedBy":"00000000-0000-0000-0000-000000000000","UserIDCreatedBy":"4a2aef16-e7d9-469a-95ad-5c8935cb6bab","PropertyCountPerLogType":0,"PhotoSource":null,"CompletionDate":new Date(-59011459200000),"QAedFlag":null,"ProjectName":"","SitePlanSrc":null,"MarketingOverview":null,"AreaDescription":null,"DeveloperAndProjectTeam":null,"BuildingFeatures":null,"OtherInformation":null,"HOADocsPDF":null,"UnitNo":null,"ImageCount":0,"PropertyImageDescription":null,"ColorSchemeCode":null,"ColorSchemeId":0,"ColorSchemeName":null,"DirectionCode":null,"DirectionDescription":null,"ViewDescription":null,"BuilderEmail":null,"LogoSource":null,"CondoImageSource":"","FloorPlanCount":0,"MasterDescription":null,"ColorSchemeCount":0}]

但是当我正在接受异常时

 org.json.JSONException: unterminated string at character 1919

即解析此行

LotDescription":"David Weekley homes Traditional Collection in Baxter Village offers floor plans featuring innovative design and unsurpassed quality. This charming community combines work, play and living, all within the Village. In Baxter Village, 

这个词中有一些特殊的字符

 you’ll 

所以,我试图用双引号(\“)替换双引号(”),代码是,

  public void ......(){
  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  HttpResponse response = client.execute(httppost);
  String jsonstring=getJSONString(response);                
  JSONArray json = new JSONArray(jsonstring);
 }
  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().replace("\"", "\\\"");

         System.out.println("Node value : " +  str);
         return str;
          }catch(Exception e){}
     }

我正在使用替换函数并用转义符号替换字符串,认为将解析特殊字符。但这似乎不起作用。

我希望整个字符串格式为\“string \”或整个字符串进行解析。我做了所有的研究并做了一些研究,但找不到任何解决方案。

请提出任何想法或建议!!提前致谢!!!

logcat是,

05-21 15:23:37.843: W/System.err(17883): org.json.JSONException: Unterminated string at character 1919 of [{"TbbId":0,"PropertyID":1066637,"BuilderID":"9250c666-e76c-4206-8b37-343b2bb11a89","BuilderName":"David Weekley Homes","Notes":"","Address":"1 TBB4519","SchoolDistrict":null,"School":null,"CityID":"Fort Mill","CountyID":"","StateID":"SC","Zip":"29708","Lat":"35.037240000000000","Lng":"-80.979742000000000","Price":364990,"PropertyStatusID":"AV","PropertyStatusDescription":"Available","StageID":"TBB","StageDescription":"To-Be-Built Home","TypeID":1,"TypeDescription":"House","SubdivisionID":4121,"SubdivisionName":"Baxter Village","FloorPlanNumber":"4519","Remarks":"","OldNew":null,"PropertyInMyListFlag":null,"FreePostingFlag":"F","PropertySubscriptionPlan":null,"PropertySubscriptionPaymentType":null,"BalanceAmount":0,"PropertyLicenseFlag":"N","PlanNumber":null,"SubdivisionFloorPlanID":null,"SubdivisionFloorPlanName":"Ridgegate","ShowDirections":"Mon-Sat 9:30am-5:30pm; Sun 12:30pm-5:30","DrivingDirections":"Take I-77, Exit 85 - Fort Mill / Highway 160. Take Highway 160 West. Proceed past the Main Baxter Village Entrance. Turn Left into Baxter Village at the next entrance marked by a white fence and stone monument which is Front Street.  Take your first right onto Richards Crossing, the David Weekley Model is located on the left at 3439 Richards Crossi","PropertyClass":"TBB","RemarksId":0,"VerifiedBU":"Y","SubdivisionDescription":null,"Contact1Name":"Traci Belk","Contact1Phone":"800-393-9968","Contact1PhoneAlt":"","Contact2Name":"","Contact2Phone":"","Contact2PhoneAlt":"","Email":"homes@dwhomes.com","Beds":4,"Baths":2,"HalfBaths":1,"Living":0,"Dining":0,"OtherRooms":"","Stories":2.0,"Master":"Down","Garage":2.0,"SquareFeet":2474,"LotSize":"","LotDescription":"David Weekley homes Traditional Collection in Baxter Village offers floor plans featuring innovative design and unsurpassed quality. This charming community combines work, play and living, all within the Village. In Baxter Village, you
05-21 15:23:37.867: W/System.err(17883):    at org.json.JSONTokener.syntaxError(JSONTokener.java:446)
05-21 15:23:37.867: W/System.err(17883):    at org.json.JSONTokener.nextString(JSONTokener.java:226)
05-21 15:23:37.867: W/System.err(17883):    at org.json.JSONTokener.nextValue(JSONTokener.java:103)
05-21 15:23:37.882: W/System.err(17883):    at org.json.JSONTokener.readObject(JSONTokener.java:381)
05-21 15:23:37.890: W/System.err(17883):    at org.json.JSONTokener.nextValue(JSONTokener.java:96)
05-21 15:23:37.898: W/System.err(17883):    at org.json.JSONTokener.readArray(JSONTokener.java:426)
05-21 15:23:37.898: W/System.err(17883):    at org.json.JSONTokener.nextValue(JSONTokener.java:99)
05-21 15:23:37.906: W/System.err(17883):    at org.json.JSONArray.<init>(JSONArray.java:87)
05-21 15:23:37.914: W/System.err(17883):    at org.json.JSONArray.<init>(JSONArray.java:103)

这是getJSONString结果,

 05-21 15:21:18.382: I/System.out(17883): Node value : [{"TbbId":0,"PropertyID":1066637,"BuilderID":"9250c666-e76c-4206-8b37-343b2bb11a89","BuilderName":"David Weekley Homes","Notes":"","Address":"1 TBB4519","SchoolDistrict":null,"School":null,"CityID":"Fort Mill","CountyID":"","StateID":"SC","Zip":"29708","Lat":"35.037240000000000","Lng":"-80.979742000000000","Price":364990,"PropertyStatusID":"AV","PropertyStatusDescription":"Available","StageID":"TBB","StageDescription":"To-Be-Built Home","TypeID":1,"TypeDescription":"House","SubdivisionID":4121,"SubdivisionName":"Baxter Village","FloorPlanNumber":"4519","Remarks":"","OldNew":null,"PropertyInMyListFlag":null,"FreePostingFlag":"F","PropertySubscriptionPlan":null,"PropertySubscriptionPaymentType":null,"BalanceAmount":0,"PropertyLicenseFlag":"N","PlanNumber":null,"SubdivisionFloorPlanID":null,"SubdivisionFloorPlanName":"Ridgegate","ShowDirections":"Mon-Sat 9:30am-5:30pm; Sun 12:30pm-5:30","DrivingDirections":"Take I-77, Exit 85 - Fort Mill / Highway 160. Take Highway 160 West. Proceed past the Main Baxter Village Entrance. Turn Left into Baxter Village at the next entrance marked by a white fence and stone monument which is Front Street.  Take your first right onto Richards Crossing, the David Weekley Model is located on the left at 3439 Richards Crossi","PropertyClass":"TBB","RemarksId":0,"VerifiedBU":"Y","SubdivisionDescription":null,"Contact1Name":"Traci Belk","Contact1Phone":"800-393-9968","Contact1PhoneAlt":"","Contact2Name":"","Contact2Phone":"","Contact2PhoneAlt":"","Email":"homes@dwhomes.com","Beds":4,"Baths":2,"HalfBaths":1,"Living":0,"Dining":0,"OtherRooms":"","Stories":2.0,"Master":"Down","Garage":2.0,"SquareFeet":2474,"LotSize":"","LotDescription":"David Weekley homes Traditional Collection in Baxter Village offers floor plans featuring innovative design and unsurpassed quality. This charming community combines work, play and living, all within the Village. In Baxter Village, you

1 个答案:

答案 0 :(得分:0)

您需要在Document doc = builder.parse();之前替换字符串,因为&amp;被视为非法角色。

因此,您需要在解析调用之前替换此字符。

      HttpEntity httpEntity = response.getEntity();
    String xml = EntityUtils.toString(httpEntity);

InputStream stream = new ByteArrayInputStream(
            (xml.replace("&", "&amp;"))
                    .getBytes("UTF-8"));
     Document doc = builder.parse(stream);

感谢。

相关问题