0

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.

5
  • 1
    Can you share whatever code you have written for this and explain what issue you are facing in that ? Commented Aug 8, 2018 at 18:47
  • @ChetanRanpariya I need the code to get this. I have not written any code. Commented Aug 8, 2018 at 18:51
  • You are only looking at parent items, you could try to iterate over the child items. stackoverflow.com/questions/26680492/… Commented Aug 8, 2018 at 18:59
  • @AnyMoose. I do not know the keys of Json. This is dynamic. I gave just sample json. Commented Aug 8, 2018 at 19:02
  • Deserialize to a Dictionary and look at the keys. Commented Aug 8, 2018 at 19:11

1 Answer 1

3

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need to make your own Flatten() extension method; you could just use the built-in Descendants() extension method instead. Fiddle: dotnetfiddle.net/szIubI

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.