I have JSON that mostly looks like the following:
{
"odata.metadata":"XXX",
"value":[
{
"PartitionKey":"0000000001-0000000001",
"RowKey":"8a6f7335-4cc7-4aaa-9b48-f719a1f56844",
"Timestamp":"2016-11-07T18:19:59.3147580Z",
"DistributionNumber":1,
"Name":"General"
},
{
"PartitionKey":"0000000001-0000000001",
"Id":"bce10165-3a3e-4166-9907-2ed02c0f83fb",
"Timestamp":"2016-11-07T18:20:17.1260274Z",
"DistributionNumber":1,
"Designation":"Secondary"
}
]
}
I say "mostly" because the JSON can vary except for the following:
odata.metadata node off the root.value node off the root which will be an array.value array can have a varied number of items, each with a variety of name-value pairs except one will always be PartitionKey.What I need to do is read the JSON into memory and strip out all the value items which do not have a PartitionKey = "0000000001-0000000001".
I have the following code so far:
var jsonObj = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonString);
var value = (ArrayList)jsonObj["value"];
foreach (var item in value)
{
if (item["PartitionKey"] != "0000000001-0000000001")
{
value.Remove(item.Key);
}
}
Casting the value as an ArrayList seems to be the only way I'm able to access its data, but then I have trouble accessing the PartitionKey property.
How can I do what I want - test each item in value and conditionally remove them - in a generic fashion since the data in each value item can be different?
I think the easiest way is to use a Dictionary<string, string> for the value properties. For example:
public class DataObject
{
[JsonProperty("odata.metadata")]
public string ODataMetadata { get; set; }
public IEnumerable<Dictionary<string, string>> Value { get; set; }
}
Now using JSON.Net:
var data = JsonConvert.DeserializeObject<DataObject>(json);
And then filter out the values you don't want:
data.Value = data.Value
.Where(v => v.Any(kvp =>
kvp.Key == "PartitionKey" && kvp.Value == "0000000001-0000000001"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With