问题
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
}
]
}
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");
But I need a solution with loop or LINQ that changes all the values, not just the first.
回答1:
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;
}
Notes:
The query string
"disbursements[*]"
contains the JSONPath wildcard operator[*]
. This operator matches all array elements under the parent element"disbursement"
.Json.NET supports JSONPath syntax as documented in Querying JSON with JSONPath.
SelectTokens() is used rather than
SelectToken()
to loop through multiple possible matches.The
JToken
item setterdisbursement["statusCode"] = 166000005
will replace the"statusCode"
property if present and add it if not.A simple, atomic value such as
166000005
can be set directly into aJToken
hierarchy. For a complex POCO you would need to call JToken.FromObject() to serialize it to aJToken
before setting it in the hierarchy, e.g.:disbursement["statusCode"] = JToken.FromObject( new { oldValue = disbursement["statusCode"], newValue = 166000005 } );
Sample working .Net fiddle.
回答2:
I would create classes to represent the data. Here is my solution:
Create the data holder classes:
public class Disbursement
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("contactId")]
public string ContactId { get; set; }
[JsonProperty("statusCode")]
public int StatusCode { get; set; }
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("category")]
public int Category { get; set; }
}
The collection:
public class Disbursements
{
[JsonProperty("disbursements")]
public List<Disbursement> Items { get; set; } = new List<Disbursement>();
}
And then the loading / modifying / saving data:
class Program
{
static void Main(string[] args)
{
var disbursements =
JsonConvert.DeserializeObject<Disbursements>(
File.ReadAllText(
"data.json",
Encoding.UTF8
)
);
foreach (var disbursement in disbursements.Items)
{
disbursement.StatusCode = 166000005;
}
string modifiedContent = JsonConvert.SerializeObject(disbursements);
File.WriteAllText(
"modifiedData.json",
modifiedContent,
Encoding.UTF8
);
}
}
来源:https://stackoverflow.com/questions/46227607/querying-json-using-selecttokens-with-newtonsoft-json-linq-in-c-sharp