从c#中的json字符串中查找一个值

时间:2013-09-06 08:47:21

标签: c# asp.net-mvc json

这是我的json字符串:

{"loginAccounts": [
    {
        "name": "abc",
        "accountId": "123456",
        "baseUrl": "https://abc.defghi.com/test/t12/remark/123456",
        "isDefault": "true",
        "userName": "Ceilina James",
        "userId": "7c5bat57-850a-5c93-39eb-2015ai9o8822",
        "email": "abc@test.com",
        "siteDescription": ""
    }
]}

我需要“baseUrl”值。如何在C#中找到它?

2 个答案:

答案 0 :(得分:6)

您可以使用JSON序列化程序(如JavaScriptSerializer类)将此JSON字符串反序列化为C#类,然后提取所需的值。例如,您可以使用以下模型:

public class SomeModel
{
    public LoginAccount[] LoginAccounts { get; set; }
}

public class LoginAccount
{
    public string Name { get; set; }
    public string AccountId { get; set; }
    public string BaseUrl { get; set; }
    public string IsDefault { get; set; }
    ...
}

然后:

string json = "... your JSON string comes here ...";
var serializer = new JavaScriptSerializer();
string json = ...
var model = (SomeModel)serializer.Deserialize(json);
foreach (var account in model.LoginAccounts)
{
    string baseUrl = account.BaseUrl;
    ...
}

答案 1 :(得分:2)

使用Json.Net

foreach (var acc in JObject.Parse(json)["loginAccounts"])
{
    Console.WriteLine(acc["baseUrl"]);
}