2014-06-22 70 views
-6

我以這種格式將一個httpwebresponse流視爲一個字符串。來自http web響應流的解析值

{"totalUsersCount": 
[{"AccountStatus":1,"TotalUsers":53,"MemberUsers":33,"CrimsonUsers":20}, 
{"AccountStatus":2,"TotalUsers":7,"MemberUsers":7,"CrimsonUsers":0}, 
{"AccountStatus":3,"TotalUsers":44,"MemberUsers":37,"CrimsonUsers":7}, 
{"AccountStatus":6,"TotalUsers":28718,"MemberUsers":28718,"CrimsonUsers":0}, 
{"AccountStatus":5,"TotalUsers":3,"MemberUsers":3,"CrimsonUsers":0}]} 

我想單獨解析出totalUsersCount的價值,使我得到的分析出結果以這種格式

[{"AccountStatus":1,"TotalUsers":53,"MemberUsers":33,"CrimsonUsers":20}, 
{"AccountStatus":2,"TotalUsers":7,"MemberUsers":7,"CrimsonUsers":0}, 
{"AccountStatus":3,"TotalUsers":44,"MemberUsers":37,"CrimsonUsers":7},  
{"AccountStatus":6,"TotalUsers":28718,"MemberUsers":28718,"CrimsonUsers":0}, 
{"AccountStatus":5,"TotalUsers":3,"MemberUsers":3,"CrimsonUsers":0}] 

如果結果是JSON格式,我們可以很容易地解析出來。但是這個結果是以字符串格式。我試圖使用Json.parse對字符串進行json化,然後應用json解析。但是這並沒有幫助。可能是我沒有嘗試正確的方式。誰能幫忙?

+2

** **怎麼沒有幫助?發生了什麼?你寫了什麼代碼? – SLaks

+0

http://james.newtonking.com/json/help/index.html?topic=html/Samples.htm# –

回答

0

我認爲你需要使用JSON.NET。它比Json的任何其他庫更好。

如果你有一個字符串,反序列化這樣

JsonObject obj = JsonConvert.DeserializeObject(stringToPass); 

它會爲您提供一個JSONObject因爲你與JsonArrays工作,試試這個

JsonArray arr = JsonConvert.DeserializeObject(stringToPass); 
// should start with [ 

更多的開發商,去這裏:http://james.newtonking.com/json

1

這很容易使用Json.Net。只需聲明你的具體類,然後反序列化。

var root = JsonConvert.DeserializeObject<RootObject>(yourJsonString); 

foreach (var item in root.TotalUsersCount) 
{ 
    Console.WriteLine(item.AccountStatus); 
} 

var allusers = root.TotalUsersCount.Sum(u => u.TotalUsers); 

public class TotalUsersCount 
{ 
    public int AccountStatus { get; set; } 
    public int TotalUsers { get; set; } 
    public int MemberUsers { get; set; } 
    public int CrimsonUsers { get; set; } 
} 

public class RootObject 
{ 
    public List<TotalUsersCount> TotalUsersCount { get; set; } 
} 

您還可以使用內置的System.Web.Script.Serialization.JavaScriptSerializer

var root = new JavaScriptSerializer().Deserialize<RootObject>(yourJsonString);