如何通过Foreach / LINQ遍历JObject属性

时间:2019-05-01 22:12:10

标签: c# json linq

我有一个已建立的JObject对象。尝试遍历它以获取基于另一个键/值的键/值(下面的json示例,当前粘贴了代码)

更多细节-希望遍历“值”,获取基于“ MailState”的“ KeyID”

绝对感觉像我显然错过了通过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
    });
}
}

2 个答案:

答案 0 :(得分:0)

您可以使用Newtonsoft.Json库来解析并循环到value的项目

下面是示例代码:

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

让我知道代码段是否有效。

答案 1 :(得分:0)

直接的方法是:

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