从http Web响应流中解析值

时间:2014-06-22 20:02:40

标签: c# json httpwebresponse

我将这种格式的httpwebresponse流作为字符串。

{"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对字符串进行jsonize,然后应用json解析。但这没有帮助。可能是我没有以正确的方式尝试。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

使用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);

答案 1 :(得分:0)

我认为你需要使用JSON.NET。它比Json的任何其他库都要好。

如果你有一个字符串,请像这样去除它

JsonObject obj = JsonConvert.DeserializeObject(stringToPass);

它会为你提供一个JsonObject,因为你正在使用JsonArrays,试试这个

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

有关开发人员的更多信息,请访问:http://james.newtonking.com/json