如何使用 Json.NET 更改 JSON 属性 的值?
How can I change the value of a JSON property using Json.NET?
我想从以下 JSON 字符串的已解析 JObject
中修改值 AREA1
和 AREA2
。
如何使用 jObject.SelectTokens()
检索元素并对其进行编辑?
{
"summary":{
"summaryDataTable":{
"id":"summaryDataTable",
"type":"dataTable",
"source":"/SmartScreen/SummaryFw",
"columns":[
{
"name":"CreateDate",
"title":"AREA1",
"filterable":false
},
{
"name":"CreateUser",
"title":"AREA2",
"filterable":false
}
],
"options":{
"showFilter":false
}
}
}
}
如果您只需要为上述 JSON 模型修改它,请使用 JObject.SelectToken
使用 JSON 路径获取父对象,然后设置如下值:
var data = JObject.Parse(json);
var firstColumn = data.SelectToken("summary.summaryDataTable.columns[0]");
var secondColumn = data.SelectToken("summary.summaryDataTable.columns[1]");
firstColumn["title"] = "replacedTitle1";
secondColumn["title"] = "replacedTitle2";
输出:
{
"summary": {
"summaryDataTable": {
"id": "summaryDataTable",
"type": "dataTable",
"source": "/SmartScreen/SummaryFw",
"columns": [
{
"name": "CreateDate",
"title": "replacedTitle1",
"filterable": false
},
{
"name": "CreateUser",
"title": "replacedTitle2",
"filterable": false
}
],
"options": {
"showFilter": false
}
}
}
}
你可以试试这个
var json= ...your json;
var o= JObject.Parse(json);
var columns=o.SelectToken("summary.summaryDataTable.columns");
columns[0]["title"]="newTitle1";
columns[1]["title"]="newTitle2";
json = o.ToString(Newtonsoft.Json.Formatting.Indented);
我想从以下 JSON 字符串的已解析 JObject
中修改值 AREA1
和 AREA2
。
如何使用 jObject.SelectTokens()
检索元素并对其进行编辑?
{
"summary":{
"summaryDataTable":{
"id":"summaryDataTable",
"type":"dataTable",
"source":"/SmartScreen/SummaryFw",
"columns":[
{
"name":"CreateDate",
"title":"AREA1",
"filterable":false
},
{
"name":"CreateUser",
"title":"AREA2",
"filterable":false
}
],
"options":{
"showFilter":false
}
}
}
}
如果您只需要为上述 JSON 模型修改它,请使用 JObject.SelectToken
使用 JSON 路径获取父对象,然后设置如下值:
var data = JObject.Parse(json);
var firstColumn = data.SelectToken("summary.summaryDataTable.columns[0]");
var secondColumn = data.SelectToken("summary.summaryDataTable.columns[1]");
firstColumn["title"] = "replacedTitle1";
secondColumn["title"] = "replacedTitle2";
输出:
{
"summary": {
"summaryDataTable": {
"id": "summaryDataTable",
"type": "dataTable",
"source": "/SmartScreen/SummaryFw",
"columns": [
{
"name": "CreateDate",
"title": "replacedTitle1",
"filterable": false
},
{
"name": "CreateUser",
"title": "replacedTitle2",
"filterable": false
}
],
"options": {
"showFilter": false
}
}
}
}
你可以试试这个
var json= ...your json;
var o= JObject.Parse(json);
var columns=o.SelectToken("summary.summaryDataTable.columns");
columns[0]["title"]="newTitle1";
columns[1]["title"]="newTitle2";
json = o.ToString(Newtonsoft.Json.Formatting.Indented);