Reputation: 59
I have following sample json string in C#
{
"AccountNumberGenerationRequest": {
"BranchNumber": 8034,
"AccountType": "041"
},
"CreateDepositAccountRequest": {
"AccountNumber": "9999999999",
"BranchNumber": 8034,
"AccountType": 41,
"WithholdingIndicator": "4"
},
"AccountNameAddressRequest": {
"AccountNumber": "9999999999",
"NameAndAddressType": 1,
},
"CustomerAccountRelationshipRequest": {
"CustomerNumber1": "58008",
"Customer1ToAccountRelationshipCode": "000"
},
"UpdatePartialInformationRequest": {
"AccountNumber": "9999999999",
"PartialInformationList": [{
"KeywordCode": "FDWTHE",
"KeywordValue": "1"
}]
},
"RequestUUID": "557d5442-8a28-4dab-b191-fe1596ddf2b8"
}
And want to read all the unique keys that has end values. Like below
["BranchNumber","AccountType","AccountNumber","BranchNumber","AccountType","WithholdingIndicator","AccountNumber","NameAndAddressType","CustomerNumber1","Customer1ToAccountRelationshipCode","KeywordCode","KeywordValue","RequestUUID"]
I am using following code
var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var json= JObject.Parse(JsonConvert.SerializeObject(p, jsonSerializerSettings));
IList<string> keys = json.Properties().Select(c=> c.Name).ToList();
foreach(string key in keys)
{
Console.WriteLine(key);
}
But getting only
AccountNumberGenerationRequest
AccountNumberGenerationRequest
AccountNameAddressRequest
AccountNameAddressRequest
UpdatePartialInformationRequest
RequestUUID
How Can I get this in C#. This is not hardcoded Json. It can be any json.
Upvotes: 0
Views: 307
Reputation: 14477
You just need to flatten the object and filter accordingly:
var uniqueKeys = json.Descendants()
.OfType<JProperty>()
.Where(x => x.Value is JValue)
.Select(x => x.Name)
.Distinct();
Upvotes: 3