删除 JSON 中在 C# asp.net 中包含多值的属性,然后再在 GridView 中显示该属性

本文关键字:属性 然后 显示 GridView 中在 JSON asp net 删除 包含多 | 更新日期: 2023-09-27 17:56:48

我是 asp.net c# 的新手。我想将 json 数据显示到带有网格视图的表中。我有这种格式的 json 数据:

[{
    "reviewerID": "A1YS9MDZP93857",
    "asin": "0006428320",
    "reviewerName": "John Taylor",
    "helpful": [
        0,
        0
    ],
    "reviewText": "last movement of sonata #6 is missing. What should one expect?",
    "overall": 3,
    "summary": "Parts missing",
    "unixReviewTime": 1394496000,
    "reviewTime": "03 11, 2014"
},
{
    "reviewerID": "A3TS466QBAWB9D",
    "asin": "0014072149",
    "reviewerName": "Silver Pencil",
    "helpful": [
        0,
        0
    ],
    "reviewText": "If you are a serious violin student on a budget, this edition has it all",
    "overall": 5,
    "summary": "Perform it with a friend, today!",
    "unixReviewTime": 1370476800,
    "reviewTime": "06 6, 2013"
}]

为了将其显示在 gridview 中,我使用以下代码(使用 Json.net 库)

JsonString = TextBox1.Text;
       dt = (DataTable)JsonConvert.DeserializeObject(JsonString, (typeof(DataTable)));
       GridView1.DataSource = dt;
       GridView1.DataBind();

问题是 gridview 无法显示数据,如果我像这样一一删除"有用"属性,它就可以了:

{
"reviewerID": "A1YS9MDZP93857",
"asin": "0006428320",
"reviewerName": "John Taylor",
"reviewText": "The portfolio is fine except for the fact that the last movement of sonata #6 is missing. What should one expect?",
"overall": 3,
"summary": "Parts missing",
"unixReviewTime": 1394496000,
"reviewTime": "03 11, 2014"}

我不知道代码怎么删除它,因为我有大量的json数据,所以我很难浪费时间手动删除它。知道吗?

删除 JSON 中在 C# asp.net 中包含多值的属性,然后再在 GridView 中显示该属性

在使用 Json.NET 时,如果要在反序列化为 DataTable 之前删除不需要的属性,则可以转换为中间 LINQ to JSON JToken分层表示形式,然后删除具有不需要的名称的属性。 完成此操作后,您可以使用 JToken.ToObject<T> 反序列化到最终的 DataTable 类。

要解析为JToken,请执行以下操作:

        var obj = JToken.Parse(JsonString);

然后按名称删除不需要的属性:

        var unwanteds = new HashSet<string>(new[] 
        {
            "helpful"
        });
        foreach (var property in obj.Children().SelectMany(o => o.OfType<JProperty>()).Where(p => unwanteds.Contains(p.Name)).ToList())
        {
            property.Remove();
        }

或者,要删除除所需属性之外的所有属性,请按名称:

        var keepers = new HashSet<string>(new[]
        {
            "reviewerID",
            "asin",
            "reviewerName",
            "reviewText",
            "overall",
            "summary",
            "unixReviewTime",
            "reviewTime",
        });
        foreach (var property in obj.Children().SelectMany(o => o.OfType<JProperty>()).Where(p => !keepers.Contains(p.Name)).ToList())
        {
            property.Remove();
        }

最后,反序列化:

        var dt = obj.ToObject<DataTable>();
相关文章: