KBNanda
KBNanda

Reputation: 665

How to get list of values by key's name across Json using C#

I have a Json file as below

{
  "objectId": "123",
  "properties": {
    "objectId": "456"
  },
  "variables": [
    {
      "objectId": "789"
    },
    {
      "objectId": "012"
    }
  ]

}

I want to get all 'objectId's in a list like [ "123", "456", "789", "012" ]

I tried as below

var body = JObject.Parse(jsonString); //using Newtonsoft library
var list = body.Properties().Where(p => p.Name == "objectId").Select(p => p.Value).ToList();

I tried in a below way too

var list = new List<string>();
            foreach(var prop in body.Properties())
            {
                if(prop.Name == "objectId")
                {
                    list.Add(prop.Value.ToString());
                }
            }

But here i get only first level properties.

Upvotes: 9

Views: 8009

Answers (4)

AmirNorsou
AmirNorsou

Reputation: 1131

 IEnumerable<JToken> AllTokens(JObject obj)
        {
            var toSearch = new Stack<JToken>(obj.Children());
            while (toSearch.Count > 0)
            {
                var inspected = toSearch.Pop();
                yield return inspected;
                foreach (var child in inspected)
                {
                    toSearch.Push(child);
                }
            }
        }

Then you can use linq to filter and perform action:

    var tokens = AllTokens(body);
    var data = tokens.Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "objectId")
    .Select(x=> ((JProperty)x).Value.Value<string>()).ToList();

Upvotes: 1

Waqas Amjad
Waqas Amjad

Reputation: 305

You can try something like this:

var jsonObject = jsonObject.Parse(json);

var key = jsonObject.Properties()
             .Where(p => p.Value.Children().Contains("V1"))
             .Select(p => p.Name)
             .FirstOrDefault();

Upvotes: 0

Peter-Yu
Peter-Yu

Reputation: 191

Use the DescendantsAndSelf().OfType() to get all JProperties, and then filter with LINQ.

var root = (JContainer)JToken.Parse(json);
            var list = root.DescendantsAndSelf().OfType<JProperty>().Where(p => p.Name == "objectId").Select(p => p.Value.Value<string>());
            Console.WriteLine(string.Join(",", list.ToArray()));

Upvotes: 8

copper spinner
copper spinner

Reputation: 43

I don’t know the JSON Objects good enough to see a simple solution using them, but with XML I would be a simple task. So a solution cold be to take this detour.

    XElement Data = JsonConvert.DeserializeXNode(JsonString);
    var List = Data.Descendants("objectId");

Upvotes: -1

Related Questions