简体   繁体   English

如何通过Foreach / LINQ迭代JObject属性

[英]How to iterate through JObject Properties via Foreach/LINQ

I have an established JObject object. 我有一个已建立的JObject对象。 Trying to loop through it to acquire a Key/value based on anothers Key/value (example of json below with code currently stuck on) 尝试循环它以获取基于其他键/值的键/值(下面的json示例,代码当前被粘住)

For a tad more detail - looking to loop through "value", get the "KeyID" based on "MailState" 对于更多细节 - 寻找循环“值”,获取基于“MailState”的“KeyID”

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 肯定觉得我错过了通过MailState / ColName过滤的步骤 - 我已经通过线程搜索了一堆但是如果有人知道一个回答这个我无法找到的人我会乐意把它拉下来/参考它

// 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
    });
}
}

You can use Newtonsoft.Json library to parse and loop to the items of value 您可以使用Newtonsoft.Json库来解析并循环到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. 如果代码段有效,请告诉我。

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 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""
            }]
        }";

            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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM