skip to Main Content

I have a variable json string which looks something like this

[{"UserId":1,"PlatformName":"A","Value_Number1":11,"Value_Number2":12}, 
 {"UserId":2,"PlatformName":"B","Value_Number1":13,"Value_Number2":14}]

raw output string

"[{"UserId":1,"PlatformName":"A","Value_Number1":11,"Value_Number2":12}, 
  {"UserId":2,"PlatformName":"B","Value_Number1":13,"Value_Number2":14}]"

I need to extract key names from this json string.

i.e userid,platfromName,Value_Number1,Value_number2

This needs to be dynamic as there will be more keys like Value_Number3,ValueNumber4 in some cases but the format will be similar.

I looked upon examples but couldn’t really relate to my scenario .

How can achieve this when number of keys and its names is not known to me .

2

Answers


  1. you can make it in one line using Newtonsoft.Json

    IEnumerable names = JArray.Parse(jsonString)
                 .SelectMany(x => ((JObject) x).Properties().Select(x =>x.Name ));
    
    Login or Signup to reply.
  2. System.Text.Json

    var json = "[{"UserId":1,"PlatformName":"A","Value_Number1":11,"Value_Number2":12},{"UserId":2,"PlatformName":"B","Value_Number1":13,"Value_Number2":14}]";
    
    using var document = JsonDocument.Parse(json);
    HashSet<string> properties = document.RootElement
        .EnumerateArray()
        .SelectMany(item => item.EnumerateObject(), (_,prop) => prop.Name)
        .ToHashSet();
    

    Result:

    UserId
    PlatformName
    Value_Number1
    Value_Number2
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search