使用JObject解析JSON

时间:2015-01-23 00:43:21

标签: c# json json.net

我需要解析一个JSON,我已经解析了记录的第一部分但是我遇到了一个子记录问题。这是我的代码:

  List<JToken> results = new List<JToken>();
        List<JToken> results2 = new List<JToken>();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
            results = JObject.Parse(result).SelectToken("record").ToList();
        }
        List<Record> users = new List<Record>();
        foreach (JObject token in results)
        {
            Record user = new Record();
            user.id = Int32.Parse(token["id"].ToString());
            user.full_name = token["full_name"].ToString();
            user.email = token["email"].ToString();

            //role.RoleName = token.SelectToken("name").ToString();

        }

这是完美的工作但我有问题解析一个更深一点的字符串。这是JSON:

{
  "record": [
   {
  "id": 2,
  "institution_id": 1,
  "full_name": "",
  "email": "",
  "role_id": 2,
  "created": "2015-01-13 01:18:52.370379",
  "updated": "2015-01-22 23:58:44.103636",
  "branch_id": 1,
  "Branch_by_branch_id": {
    "id": 1,
    "institution_id": 1,
    "branch_name": "Test Branch"
  }
}

] }

我想在Branch_by_branch_id中获取“branch_name”。如何使用Jobject访问它?

1 个答案:

答案 0 :(得分:1)

如果你的JSON是这个

{
    "record": [
        {
            "id": 26,
            "full_name": "",
            "email": "",
            "branch_id": 1,
            "Branch_by_branch_id": {
                "id": 1,
                "institution_id": 1,
                "branch_name": "NAME"
            }
        }
    ]
}

有这样的课程:

public class BranchByBranchId
{
    public int id { get; set; }
    public int institution_id { get; set; }
    public string branch_name { get; set; }
}

public class Record
{
    public int id { get; set; }
    public string full_name { get; set; }
    public string email { get; set; }
    public int branch_id { get; set; }
    public BranchByBranchId Branch_by_branch_id { get; set; }
}

public class RootObject
{
    public List<Record> record { get; set; }
}

然后解析它并检索这样的值。

var root = JsonConvert.DeserializeObject<RootObject>(json);
var branchName = root[0].Branch_by_branch_id.branch_name;

我总是喜欢像这样访问我的JSON对象,因为我喜欢将我的对象作为本机C#类。这些类由json2csharp生成。