I have the JSON Response below as an example and I need to store how many times the System.State has changed from x to y. The end result will be storing the date in a file for reporting purposes.
Please could you advise how I can achieve this in C#.
{
"count": 6,
"value": [
{
"id": 1,
"workItemId": 226,
"rev": 1,
"revisedBy": {
"id": "0e7735b9-cf6a-6468-82c1-81e6b092addd",
"descriptor": "aad.MGU3NzM1YjktY2Y2YS03NDY4LTgyYzEtODFlNmIwOTJhZGRk"
},
"revisedDate": "2020-05-22T09:49:00.81Z",
"fields": {
"System.Id": {
"newValue": 226
},
"System.Reason": {
"newValue": "New"
},
"System.CreatedDate": {
"newValue": "2020-05-22T07:59:22.64Z"
},
"System.ChangedDate": {
"newValue": "2020-05-22T07:59:22.64Z"
}
}
},
{
"id": 2,
"workItemId": 226,
"rev": 2,
"revisedDate": "2020-05-22T09:49:04.45Z",
"fields": {
"System.Rev": {
"oldValue": 1,
"newValue": 2
},
"System.State":{
"oldValue":"New",
"newValue":"Resolved"
}
}
}
]
}
CodePudding user response:
You can create a JArray object then loop throuht and do whatever you want like :
var values = (JArray)jObject["value"]; //jObject is your json passed in parameter
var items = values.Select(x => new Item
{
Id= x["id"]?.Value<int>(),
...
Fields = new Fields
{
State = new State
{
x["fields"]?["System.State"]?["newValue"]?.Value<string>(),
...
}
}
});
Then you can manipulate it like you want.
CodePudding user response:
You can deserialize your JSON to strongly typed models and then apply your logic to log the times where the state has changed. Since your JSON data is not consistent, you need to be aware of the nulls for some fields.
An example with your JSON string is: 
CodePudding user response:
try this
var jp= JObject.Parse(json)["value"];
var count=0;
foreach (var item in jp)
{
var systemState = ((JObject) ((JObject)item).Properties()
.FirstOrDefault(p=>p.Name=="fields").Value).Properties()
.Where(v => v.Name == "System.State")
.Select(v=>v.Value).FirstOrDefault();
if ( systemState!=null
&& (string) systemState["oldValue"] != (string) systemState["newValue"]) count ;
}
result
count=1
