2016-12-29 16 views
-1

對於正則表達式我很新穎。我想篩選出一個Http GetRequest字符串,並將這些標記作爲一個Dictionary對象返回,這樣我就可以找到每個標記。例如,返回的字符串如下如何使用正則表達式和LINQ返回c中的字典對象#

「{\」 CURRENCYCODE \ 「:\」 CAD \」,\ 「ID \」:\ 「29BKR08JSRJ5BE11LD \」,\ 「鏈接\」:[{\ 「rel \」:\「hosted_pa​​yment \」,\「uri \」:\「https://pay.test.netbanx.com/hosted/v1/payment/53616c7465645f5fcb770fe4ad39262c27ae2fba4189e1ef89aacc3fac4e0fc0ba7d1699c4a50672 \」},{\「rel \」:\「self \」,\「uri \」:\「https ... \ 「},{\」rel \「:\」resend_callback \「,\」uri \「:\」https://37520-1001043850:B-qa2-0-56797b63-0-302c02147c32c6cad7f273be1c06c[email protected]api.test.netbanx.com/hosted/v1/orders/29BKR08JSRJ5BE11LD/resend_callback \「}],\」merchantRefNum \「:\」fd63cb9d-b586-664d-9bba-8492baf4bad9 \ \「mode \」:\「live \」,\「totalAmount \」:\「100 \」,\「type \」:\「order \」}

我想返回currencyCode as密鑰和CAD作爲價值。這同樣適用於連桿,相對=> hosted_pa​​yment,URI => https://開頭.....

我使用下列但它不是我想要提前

Regex regex = new Regex(@"((""((?<token>.*?)(?<!\\)"")|(?<token>[\w]+))(\s)*)", 
     RegexOptions.None); 

return (from Match m in regex.Matches(orderResp) 
    where m.Groups["token"].Success 
    select m.Groups["token"].Value).ToArray(); 

謝謝

+7

羅像JSON一樣。你爲什麼不解析它? –

+0

謝謝。我得到了我的回答 – Zukunft

回答

2

我同意從吉榮Vannevel commentar,你可以簡單地用Json.net解析您的JSON:

var parsed = JObject.Parse(orderResp); 
var code = parsed["currencyCode"]; 
0
using System.Collections.Generic; 
using System.Diagnostics; 
using System.Web.Script.Serialization; 

namespace Chinenye 
{ 
    class Program 
    { 
     static void Main() 
     { 
      var objectString = "{\"currencyCode\":\"CAD\",\"id\":\"29BKR08JSRJ5BE11LD\",\"link\":[{\"rel\":\"hosted_payment\",\"uri\":\"https://pay.test.netbanx.com/hosted/v1/payment/53616c7465645f5fcb770fe4ad39262c27ae2fba4189e1ef89aacc3fac4e0fc0ba7d1699c4a50672\"},{\"rel\":\"self\",\"uri\":\"https...\"},{\"rel\":\"resend_callback\",\"uri\":\"https://37520-1001043850:B-qa2-0-56797b63-0-302c02147c32c6cad7f273be1c06c[email protected]api.test.netbanx.com/hosted/v1/orders/29BKR08JSRJ5BE11LD/resend_callback\"}],\"merchantRefNum\":\"fd63cb9d-b586-664d-9bba-8492baf4bad9\",\"mode\":\"live\",\"totalAmount\":\"100\",\"type\":\"order\"}"; 

      JavaScriptSerializer serializer = new JavaScriptSerializer(); 

      var o = serializer.Deserialize<HttpObject>(objectString); 

      Debugger.Break(); 
     } 
    } 

    class HttpObject 
    { 
     public string currencyCode; 
     public string id; 
     public List<Link> link; 
     public string merchantRefNum; 
     public string mode; 
     public string totalAmount; 
     public string type; 
    } 

    class Link 
    { 
     public string rel; 
     public string uri;  
    } 
} 
+0

謝謝。這絕對有助於:) – Zukunft

相關問題