5

我正在使用 Json.net 进行序列化,然后制作一个如下所示的 JObject:

 "RegistrationList": [
    {
      "CaseNumber": "120654-1330",
      "Priority": 5,
      "PersonId": 7,
      "Person": {
        "FirstName": "",
        "LastName": "",
      },
      "UserId": 7,
      "User": {
        "Id": 7,
        "CreatedTime": "2013-07-05T13:09:57.87",
        "Comment": "",
    },

我如何将其查询到一个新的对象或列表中,这很容易放入一些 html 表/视图中。我只想显示 CaseNumber、FirstName 和 Comment。

4

4 回答 4

6

我只想显示 CaseNumber、FirstName 和 Comment。

在 ASP.NET MVC 中,您可以从编写符合您要求的视图模型开始:

public class MyViewModel
{
    public string CaseNumber { get; set; }
    public string FirstName { get; set; }
    public string Comment { get; set; }
}

然后在您的控制器操作中,您从已有的 JObject 实例构建视图模型:

public ActionResult Index()
{
    JObject json = ... the JSON shown in your question (after fixing the errors because what is shown in your question is invalid JSON)

    IEnumerable<MyViewModel> model =
        from item in (JArray)json["RegistrationList"]
        select new MyViewModel
        {
            CaseNumber = item["CaseNumber"].Value<string>(),
            FirstName = item["Person"]["FirstName"].Value<string>(),
            Comment = item["User"]["Comment"].Value<string>(),
        };

    return View(model);
}

最后在您的强类型视图中显示所需的信息:

@model IEnumerable<MyViewModel>

<table>
    <thead>
        <tr>
            <th>Case number</th>
            <th>First name</th>
            <th>Comment</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.CaseNumber</td>
                <td>@item.FirstName</td>
                <td>@item.Comment</td>
            </tr>
        }
    </tbody>
</table>
于 2013-07-22T07:42:48.057 回答
2

几种方式:

1) 根据文档“使用 LINQ for JSON ”,您可以以 LINQ 方式查询 JObject

JObject o = JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");

string cpu = (string)o["CPU"];
// Intel

string firstDrive = (string)o["Drives"][0];
// DVD read/writer

IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive

2)使用 SelectToken 查询 JSON

3)使用自定义辅助扩展方法按指定路径查询,如下所示:

public static class JsonHelpers
{
    public static JToken QueryJson(this object jsonObject, params string[] jsonPath)
    {
        const string separator = " -> ";

        if (jsonObject == null)
            throw new Exception(string.Format("Can not perform JSON query '{0}' as the object is null.",
                string.Join(separator, jsonPath ?? new string[0])));

        var json = (jsonObject as JToken) ?? JObject.FromObject(jsonObject);
        var token = json;
        var currentPath = "";

        if (jsonPath != null)
            foreach (var level in jsonPath)
            {
                currentPath += level + separator;
                token = token[level];
                if (token == null) break;
            }

        if (token == null)
            throw new Exception(string.Format("Can not find path '{0}' in JSON object: {1}", currentPath, json));

        return token;
    }
}
于 2014-09-15T15:16:46.287 回答
0

我想你想得到如下的 JSON 字符串:

{
'RegistrationList': [       
            {
                'CaseNumber': '120654-1330',
                                    'Priority': 5,
                                    'PersonId': 7,
                                    'Person': {
                                        'FirstName': '0',
                                        'LastName': '',
                                    },
                                    'UserId': 7,
                                    'User': {
                                        'Id': 7,
                                        'CreatedTime': '2013-07-05T13:09:57.87',
                                        'Comment': ''
                                    }
                                },
                                {
                                    'CaseNumber': '120654-1330',
                                    'Priority': 5,
                                    'PersonId': 7,
                                    'Person': {
                                        'FirstName': '0',
                                        'LastName': '',
                                    },
                                    'UserId': 7,
                                    'User': {
                                        'Id': 7,
                                        'CreatedTime': '2013-07-05T13:09:57.87',
                                        'Comment': ''
                                    }
                                },
                            ]
}

如果是这样,您可以获得以下代码来解决您的问题:

            string json = @"{
                            'RegistrationList': [
                                {
                                    'CaseNumber': '120654-1330',
                                    'Priority': 5,
                                    'PersonId': 7,
                                    'Person': {
                                        'FirstName': '0',
                                        'LastName': '',
                                    },
                                    'UserId': 7,
                                    'User': {
                                        'Id': 7,
                                        'CreatedTime': '2013-07-05T13:09:57.87',
                                        'Comment': ''
                                    }
                                },
                                {
                                    'CaseNumber': '120654-1330',
                                    'Priority': 5,
                                    'PersonId': 7,
                                    'Person': {
                                        'FirstName': '0',
                                        'LastName': '',
                                    },
                                    'UserId': 7,
                                    'User': {
                                        'Id': 7,
                                        'CreatedTime': '2013-07-05T13:09:57.87',
                                        'Comment': ''
                                    }
                                },
                            ]
                        }";
        JObject o = JObject.Parse(json);
        JArray list = (JArray)o["RegistrationList"];
        List<Tuple<string, string, string>> rList = new List<Tuple<string, string, string>>();
        foreach (var r in list)
        {
            Tuple<string, string, string> temp = new Tuple<string, string, string>(r["CaseNumber"].Value<string>(), r["Person"]["FirstName"].Value<string>(), r["User"]["Comment"].Value<string>());
            rList.Add(temp);
            Console.WriteLine(temp);
        }
于 2013-07-22T08:26:11.777 回答
-2

    var serializer = new JavaScriptSerializer();
    对象模型数据 = serializer.DeserializeObject(jsonstring);

于 2013-07-22T07:37:24.800 回答