简体   繁体   English

如何使用 C# 从 JSON 中删除键值

[英]How to remove remove key value from JSON using C#

I have a json response that I will need to edit before binding to a GridView.我有一个 json 响应,我需要在绑定到 GridView 之前对其进行编辑。 I'm using Newtonsoft JSON library.我正在使用 Newtonsoft JSON 库。 The data binds perfectly to the GridView when "values" are removed from the string.当从字符串中删除“值”时,数据完美地绑定到 GridView。 When values is added to the json response I get this error message.将值添加到 json 响应时,我收到此错误消息。

Message=Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.

How can I remove "values" from jsonResponse before binding to GridView?如何在绑定到 GridView 之前从 jsonResponse 中删除“值”?

<asp:GridView ID="gvJson" runat="server" BackColor="White" BorderColor="#3399ff"
        BorderStyle="Dotted" BorderWidth="1px" CellPadding="3" GridLines="Both" AutoGenerateColumns="true"></asp:GridView>

    var jsonResponse = "{\"values\":[{\"id\":\"201\",\"name\":\"Zack\"},{\"id\":\"158\",\"name\":\"Kim\"},{\"id\":\"254\",\"name\":\"Scott\"}]}";

    DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(jsonResponse);

    gvJson.DataSource = dataTable;
    gvJson.DataBind();

My JSON:我的 JSON:

{
    "values": [
        {
            "id": "201",
            "name": "Zack"
        },
        {
            "id": "158",
            "name": "Kim"
        },
        {
            "id": "254",
            "name": "Scott"
        }
    ]
}

There are a couple of ways to do this..有几种方法可以做到这一点..

You could use JObject你可以使用JObject

var dataTable = JObject
      .Parse(jsonResponse)["values"]
      .ToObject<DataTable>();

Or as been suggested, fully deserialize the Json to concrete classes and bind the array to control directly或者按照建议,将 Json 完全反序列化到具体类并将数组绑定到直接控制

Given给定

public class Value    
{
   public string id { get; set; } 
   public string name { get; set; } 
}

public class Root   
{
   public List<Value> values { get; set; } 
}

Usage用法

var root = JsonConvert.DeserializeObject<Root>(jsonResponse);
// your Data , root.Data

Instead of removing the values from JSON response, you should be able to do something like而不是从 JSON 响应中删除values ,您应该能够执行类似的操作

var jsonObject = JObject.Parse(jsonResponse);
var dataTable = JsonConvert.DeserializeObject<DataTable>(jsonObject["values"].ToString());

gvJson.DataSource = dataTable;
gvJson.DataBind();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM