Search code examples
jsonlinqc#-4.0json.netesri

Using Linq to Get List of Strings from Json


I've got this JSON (below) and I'm having trouble selecting a list of string that would be "MARYLAND", "NEW YORK", "PENNSYLVANIA".

    {
  "displayFieldName": "NAME",
  "fieldAliases": {
    "STATE": "STATE"
  },
  "fields": [
    {
      "name": "STATE",
      "type": "esriFieldTypeString",
      "alias": "STATE",
      "length": 20
    }
  ],
  "features": [
    {
      "attributes": {
        "STATE": "Maryland"
      }
    },
    {
      "attributes": {
        "STATE": "New York"
      }
    },
    {
      "attributes": {
        "STATE": "Pennsylvania"
      }
    }
  ]
}

So far I'm getting the json string and deserializing it to a JObject and I can see the children. I'm having trouble going much further with it though and it doesn't fit with may other examples I've seen because the "features" are a collection of "attributes". I'm having trouble writing the linq to get down to the next level.

Here's my code:

            var foo = response.Content.ReadAsStringAsync().Result;

            var json = (JObject)JsonConvert.DeserializeObject(foo);

            var cf = json["features"].Children();

Can anybody help me with the linq statement to get the string of states from this?

Thanks


Solution

  • Assuming your JObject class looks somehow like in the sample below, you could do the following:

    string[] states = json.features.SelectMany(f => f.attributes).ToArray();
    

    This yields a single array with the three entries Maryland, New York and Pennsylvania.

    Full sample:

    class JObject
    {
        public Feature[] Features { get; set; }
    }
    
    class Feature
    {
        public string[] Attributes { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Feature f1 = new Feature { Attributes = new[] { "Maryland" } };
            Feature f2 = new Feature { Attributes = new[] { "New York" } };
            Feature f3 = new Feature { Attributes = new[] { "Pennsylvania" } };
    
            JObject state = new JObject
            {
                Features = new[] { f1, f2, f3 }
            };
    
            string[] states = state.Features.SelectMany(f => f.Attributes).ToArray();
        }
    }