Jazzkatt
Jazzkatt

Reputation: 65

How to iterate through JObject Properties via Foreach/LINQ

I have an established JObject object. Trying to loop through it to acquire a Key/value based on anothers Key/value (example of json below with code currently stuck on)

For a tad more detail - looking to loop through "value", get the "KeyID" based on "MailState"

definitely feel like I am missing the step of filtering by MailState/ColName apparently - I have searched through threads a bunch but if someone knows of one that answered this that i was unable to find i will happily pull this down/reference it

// JSON DATA
{
    "odata.metadata": "https://..com/odata/$metadata#JCJMCDXes",
    "value": [
        {
            "KeyID": "10379",
            "MailCity": "Chicago",
            "MailState": "IL"
        },
        {
            "KeyID": "9846",
            "MailCity": "Chicago",
            "MailState": "IL"
        },
        {
            "KeyID": "2234",
            "MailCity": "Madison",
            "MailState": "WI"
        }]
}

// Current code example

// class in play
public class datastorage
{
  public string ID { get; set; }
  public string Col { get; set; }
}

public class listData
{
  public string ColName {get;set;}
}

// getVPData is a string response from a call to an API
getVPData.Replace(System.Environment.NewLine, "");

JObject jobj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(getVPData);

List<datastorage> data = new List<datastorage>();

// Loop
foreach(var r in listData) // has distinct State abeviations so only 1 occurence
{
foreach (var j in jobj) // This the right path?
{
  //add KeyID into ID
  data.add(new datastorage
    {
     ID = ,//add KeyID into ID
     Col = r.ColName
    });
}
}

Upvotes: 0

Views: 4563

Answers (2)

vladimir
vladimir

Reputation: 15246

Straightforward ways are:

using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ConsoleApp7
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var mailStates = new[] {"IL", "WI"};    
            var jObject = (JObject) JsonConvert.DeserializeObject(json);
            var values = (JArray) jObject["value"];
                
            // 1st way

            foreach (var mailState in mailStates)
            {
                var key = values
                    .Where(v => mailState == v.SelectToken("MailState").Value<string>())
                    .Select(v => v.Value<string>("KeyID"))
                    .FirstOrDefault();

                Console.WriteLine($"1st case: {mailState} - {key}");
            }

            /* 2nd way based on JSONPath
             * api: https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm
             * dox: https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html
             * tester: https://jsonpath.curiousconcept.com/
             */

            foreach (var mailState in mailStates)
            {
                var key = values.SelectTokens($"$[?(@.MailState == '{mailState}')].KeyID")
                    .Select(v => v.ToString())
                    .FirstOrDefault();

                Console.WriteLine($"2nd case: {mailState} - {key}");
            }

            Console.ReadKey();
        }


    private static string json = @"
    {
    ""odata.metadata"": ""https://cdxapiclient.palmercg.com/odata/$metadata#JCJMCDXes"",
            ""value"": [
            {
                ""KeyID"": ""10379"",
                ""MailCity"": ""Chicago"",
                ""MailState"": ""IL""
            },
            {
                ""KeyID"": ""9846"",
                ""MailCity"": ""Chicago"",
                ""MailState"": ""IL""
            },
            {
                ""KeyID"": ""2234"",
                ""MailCity"": ""Madison"",
                ""MailState"": ""WI""
            }]
        }";
    }
}

Upvotes: 1

Jeric Cruz
Jeric Cruz

Reputation: 1909

You can use Newtonsoft.Json library to parse and loop to the items of value

here is a sample code:

dynamic json = JsonConvert.DeserializeObject(getVPData);
foreach (dynamic item in json["value"])
{
   //you can access the fields inside value.
    var KeyID = item["KeyID"];
    var MailCity = item["MailCity"];
    var MailState = item["MailState"];

    //just for showing...
    Console.WriteLine("KeyID:{0}, MailCity:{1}, MailState:{2}", KeyID, MailCity, MailState);
}

Let me know if the snippet works.

Upvotes: 1

Related Questions