使用SelectTokens查询JSON?使用C#中的Newtonsoft.Json.Linq [英] Querying JSON using SelectTokens? With Newtonsoft.Json.Linq in C#

查看:596
本文介绍了使用SelectTokens查询JSON?使用C#中的Newtonsoft.Json.Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#中的Netwonsoft.JSON.Linq来更改以下JSON中的"statusCode"值:

I'm trying to make use of Netwonsoft.JSON.Linq in C#, to change the "statusCode" values in the following JSON:

{  
   "disbursements":[  
      {  
         "id":"1f337641",
         "contactId":"f5eb2",
         "statusCode":166000005,
         "amount":8,
         "category":166000001
      },
      {  
         "id":"027a4762",
         "contactId":"f5eb2038",
         "statusCode":166000000,
         "amount":4000,
         "category":166000000
      }
   ]
}

因此,在JSON数据内是:"disdissements",它是JSON数组.我必须将数组中每个项目的"statusCode"更改为166000005.我可以使用

So, inside the JSON data is: "disbursements" which is JSON array. I have to change the "statusCode" of each item in the array to 166000005. I'm able to retrieve statusCode of the first one using

JObject jsonText = JObject.Parse(bodyText);
var statusCode = (int)jsonText.SelectToken("disbursements[0].statusCode");

但是我需要一个使用循环或LINQ的解决方案来更改所有值,而不仅仅是第一个.

But I need a solution with loop or LINQ that changes all the values, not just the first.

推荐答案

以下代码将"statusCode": 166000005设置或添加到支出数组中的每个条目:

The following code sets or adds "statusCode": 166000005 to every entry in the disbursement array:

var jsonText = JObject.Parse(bodyText);
foreach (var disbursement in jsonText.SelectTokens("disbursements[*]"))
{
    disbursement["statusCode"] = 166000005;
}

注意:

  • 查询字符串"disbursements[*]"包含 JSONPath 通配符[*].此运算符匹配父元素"disbursement"下的所有数组元素.

  • The query string "disbursements[*]" contains the JSONPath wildcard operator [*]. This operator matches all array elements under the parent element "disbursement".

Json.NET支持JSONPath语法,如使用JSONPath查询JSON .

Json.NET supports JSONPath syntax as documented in Querying JSON with JSONPath.

SelectTokens() 而不是SelectToken()循环遍历多个可能的匹配项.

SelectTokens() is used rather than SelectToken() to loop through multiple possible matches.

JToken 项目设置器 将替换"statusCode"属性(如果存在),然后添加"statusCode"属性.

The JToken item setter disbursement["statusCode"] = 166000005 will replace the "statusCode" property if present and add it if not.

一个简单的原子值(例如166000005)可以直接设置为JToken层次结构.对于复杂的POCO,您需要调用 JToken.FromObject() 进行序列化在层次结构中将其设置为JToken之前,例如:

A simple, atomic value such as 166000005 can be set directly into a JToken hierarchy. For a complex POCO you would need to call JToken.FromObject() to serialize it to a JToken before setting it in the hierarchy, e.g.:

disbursement["statusCode"] = 
    JToken.FromObject( new { oldValue = disbursement["statusCode"], newValue = 166000005 } );

示例工作 .Net小提琴.

这篇关于使用SelectTokens查询JSON?使用C#中的Newtonsoft.Json.Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆