2012-12-18 74 views
15

我正在嘗試使用JSON從服務器獲取一個對象數組。從字符串中刪除所有匹配項

服務器向我發送以下字符串。現在

"[{\"DealComment\":null,\"DealVotes\":[],\"DealId\":1,\"CompanyId\":1,\"StartDate\":\"2012-12-13T00:00:00\",\"EndDate\":\"2012-12-16T00:00:00\",\"CouponCode\":\"Test Coupon 1\",\"Description\":\"Test Deal Description 1\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 1\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":2,\"CompanyId\":1,\"StartDate\":\"2012-12-16T00:00:00\",\"EndDate\":\"2012-12-17T00:00:00\",\"CouponCode\":\"Test Coupon 2\",\"Description\":\"Test Description 2\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 2\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":3,\"CompanyId\":1,\"StartDate\":\"2012-12-14T00:00:00\",\"EndDate\":\"2012-12-15T00:00:00\",\"CouponCode\":\"Test Code 3\",\"Description\":\"Test Description 3\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 3\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":4,\"CompanyId\":1,\"StartDate\":\"2012-12-12T00:00:00\",\"EndDate\":\"2012-12-13T00:00:00\",\"CouponCode\":\"Test Coupon 4\",\"Description\":\"Test Description 4\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 4\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":5,\"CompanyId\":2,\"StartDate\":\"2012-12-12T00:00:00\",\"EndDate\":\"2012-12-14T00:00:00\",\"CouponCode\":\"AwD\",\"Description\":\"Very awesome deal!\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Awesome Deal 1\"}]" 

,如果你在字符串仔細觀察,你會發現它包含一個\",而不是每"。該字符串現在無法格式化爲JSONArray。所以,我需要"更換的\"每一次出現,這將有一個非常簡單的任務,有\沒有一個轉義序列

我試着用下面的代碼。

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

但它給了我以下例外。

12-19 00:35:59.575: W/System.err(444): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1: 
12-19 00:35:59.575: W/System.err(444): \ 
12-19 00:35:59.575: W/System.err(444):^

我的整個代碼,在情況下,它是任何使用的:

public void getAllDealsFromServerJson() 
    { 

     String apiUrl = "http://passme.azurewebsites.net/api/TestApi/"; 


     HttpClient client = new DefaultHttpClient(); 
     HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit 
     HttpResponse response; 
     JSONObject json = new JSONObject(); 

     try{ 
      HttpPost httpPost = new HttpPost(apiUrl); 
      json.put("requestType", "getalldeals"); 

      StringEntity se = new StringEntity(json.toString()); 
      se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
      httpPost.setEntity(se); 
      response = client.execute(httpPost); 
      Log.d("Http Response:", response.toString()); 
      jsonResponse = response.toString(); 

      BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
      String jsonStr = reader.readLine(); 
      Log.d("String Response", jsonStr); 
      String jsonFormattedString = jsonStr.replaceAll("\\", ""); // gives error 
      Log.d("Formatted String", jsonFormattedString); 
      //JSONTokener tokener = new JSONTokener(jsonFormattedString); 
      /*JSONObject finalResult = new JSONObject(tokener); 
      Log.d("JSON Response", "" + finalResult.optString("Title"));*/ 
      JSONArray resultArray = new JSONArray(jsonFormattedString); 
      Log.d("JSON Array Result Length", "" + resultArray.length()); 
      Log.d("JSON Array Result ", "" + resultArray.getJSONObject(0).optInt("DealId")); 

     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 



    } 

回答

23

嘗試這種情況:

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

由於反斜槓是在正則表達式的轉義字符(replaceAll()接收一個作爲參數),它也必須被轉義。

+1

真棒!像魅力一樣工作!謝謝你一噸先生! – Swayam

+2

'String jsonFormattedString = jsonStr.replace('\\','');'因爲您沒有雙重轉義而更容易。 Docs說:返回一個新字符串,它是用newChar替換這個字符串中的所有oldChar。 –

+1

@mikejones如果你從問題中注意到,那是OP最初做的事,它不起作用。 –

5

它看起來像你的傳入字符串是雙JSON編碼。你應該解碼它,然後再解碼。

這是我最好的猜測,你可能會怎麼做,在Java中:

JSONArray resultArray = new JSONArray(new JSONString(jsonFormattedString)); 

我在這裏假設JSONString是一種類型。你的實際解決方案可能有所不同

在正常情況下,我希望有一項服務可以直接爲您提供JSON。看起來這個服務給你一個字符串(根據JSON規範編碼),其中包含 JSON。

這是下面的區別:額外的前端和後端的報價

String someJSON = "[0, 1, 2]"; 
String doublyEncodedJSON = "\"[0, 1, 2]\""; 

通知?這是因爲後者是一串JSON。你必須解碼它兩次才能得到實際的物體。

+0

我該怎麼做,先生? – Swayam

+0

添加我最好的猜想---我不經常做Java開發,但我每天都使用JSON。祝你好運! – jimbojw

+0

那麼,實際上是先生..我剛剛取代了「與」,並在這裏http://www.jsoneditoronline.org/測試結果字符串。它正確地顯示了,我期望的方式。 – Swayam

3

你可以使用:

str.replace("\\",""); 

需要替換字符串作爲PARAM,使用的replaceAll正則表達式。它可能像這樣工作也:

str.replaceAll("\\\\", ""); 
+0

謝謝你的回答。我用第一個答案來解決問題。無論如何感謝! :) – Swayam

11

其實,正確的方法是:

String jsonFormattedString = jsonStr.replace("\\\"", "\""); 

您是否希望什麼(它會吃掉僅更換\"",並非所有\你在json字符串中跳過,如果有的話)。 與流行相反,replace(...)也會替換所有出現的字符串,就像replaceAll(...)一樣,它只是不使用正則表達式,因此通常會更快。

+0

哦。沒有意識到這一點。但不是它取代\「與」相同? – Swayam

+0

感謝您的幫助。 –

+0

@Swayam是的,如果我們假設給定的json不會在任何地方包含'\' –

3

只需使用:

try { 
     jsonFormattedString = new JSONTokener(jsonString).nextValue().toString(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

查看文檔

+0

這將是正確的方法,而不是使用正則表達式或字符串替換\\。 – Soumya

0
jsonObj.toString() 
     .replace("\"[", "[").replace("]\"", "]") 
     .replace("\\\"{", "{").replace("}\\\"", "}") 
     .replace("\\\\\\\"", "\"") 
相關問題