2010-04-12 107 views
0

有沒有辦法查詢特定項目的JSON(String)?查詢JSON字符串

即:

String jSon = "{\"a\":{\"b\":27472483,\"c\":\"123\"}}"; 

這樣的:

Int32 bob = (Int32)getFromJSON("a.b", jSon); 
// bob == 27472483 

謝謝 -Theo

回答

0
public T getFromJSON<T>(String sel, String jSon) 
    { 
     String[] id = sel.Split('.'); 
     Object tmp = jSon; 

     for (int i = 0; i < id.Length; i++) 
     { 
      tmp = tmp.ToString().Split(new string[] { "\"" + id[i] + "\":" }, StringSplitOptions.None)[1]; 
     } 

     Boolean isString = false; 
     if (tmp.ToString().StartsWith("\"")) 
     { 
      tmp = tmp.ToString().Substring(1); 
      isString = true; 
     } 

     tmp = tmp.ToString().Split(new char[] { '}', ']', '"' }, StringSplitOptions.None)[0]; 

     if (!isString && tmp.ToString().EndsWith(",")) 
      tmp = tmp.ToString().Substring(0, tmp.ToString().Length - 1); 

     if (typeof(T) == typeof(Int32)) 
      tmp = Int32.Parse(tmp.ToString()); 

     return (T)tmp; 
    } 

v0.7b作品!

1

你想在這裏做的是JSON字符串反序列化到C#對象,然後從那裏訪問'b'屬性。 More on that here

+2

這個我知道該怎麼做,但這意味着你必須定義你想要事先查詢的每個對象。 – 2010-04-12 14:57:33

+2

最常見的原因是它基於通過第三方API返回的JSON,因此在開發其服務時定義會不斷變化。 – 2010-04-12 14:59:48

+0

@Theofanis Pantelides:好吧,那麼這裏有一個關於不同解決方案的有趣例子(第一個,對於C#2.0,不是解決方案):http://blogs.msdn.com/alexghi/archive/2008/12/ 22 /使用匿名類型對反序列化-JSON-data.aspx – 2010-04-13 06:16:38