Search for Key & Value in JSON using C# code 在C#代码中搜索JSON中的键和值

huangapple go评论84阅读模式
英文:

Search for Key & Value in JSON using C# code

问题

Sure, here's the translated code portion:

我有以下的 JSON

{
    "Company": {
        "tech": {
            "star": "abc.com",
            "star1": "def.com",
            "star2": "ghi.com"
        },
        "non tech": {
            "graphic": "media.com",
            "content": "xyz.com"
        },
        "City": "City1.com"
    }
}

我正在使用以下代码来读取 JSON 文件,但目前无法递归读取并到达内部层级。我只能获取第一层的键和值,对于上面的示例,for 循环运行了两次。每当遇到链接时,我需要将其添加到字典中,但为此我必须到达内部层级:

string jsonFilePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "demo.json");

string json = File.ReadAllText(jsonFilePath);

Elements = (JObject)JsonConvert.DeserializeObject(json);

findJsonValues(Elements);

private Dictionary<string, string> findJsonValues(JObject Cat)
{
    foreach (var pair in Cat)
    {
        string sKey = pair.Key;
        string ss = Cat[sKey].ToString();
        if (ss.StartsWith("https"))
        {
            Console.WriteLine("Hey");
            Link = ss;
            linkDictionary.Add(sKey, ss);
            jsonIntentLimit++;
            if (jsonIntentLimit == 3)
            {
                // 调用一个函数
            }
            continue;
        }
        jsonValues(context, (JObject)pair.Value);
    }
}

If you have any specific questions or need further assistance, please feel free to ask.

英文:

I have below json:

{
&#160; &#160;&quot;Company&quot;: {
&#160; &#160; &#160; &quot;tech&quot;: {
&#160; &#160; &#160; &#160; &#160;&quot;star&quot;: &quot;abc.com&quot;,
&#160; &#160; &#160; &#160; &#160;&quot;star1&quot;: &quot;def.com&quot;,
&#160; &#160; &#160; &#160; &#160;&quot;star2&quot;: &quot;ghi.com&quot;
&#160; &#160; &#160; },
&#160; &#160; &#160; &quot;non tech&quot;: {
&#160; &#160; &#160; &#160; &#160;&quot;graphic&quot;: &quot;media.com&quot;,
&#160; &#160; &#160; &#160; &#160;&quot;content&quot;: &quot;xyz.com&quot;
&#160; &#160; &#160; &#160; &#160;
&#160; &#160; &#160; },

      &quot;City&quot;: &quot;City1.com&quot;,
	  
&#160; &#160;},
}

I am using below code to read the json file ,but currently unable to read recursively and reach to inner level
I am only able to get the first level key and value and for loop runs 2 times for the above example,Whenever a link is encountered then i have to add that in dictionary ,but for that i have to reach to inner level:

string jsonFilePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), &quot;demo.json&quot;);

string json = File.ReadAllText(jsonFilePath);

Elements= (JObject)JsonConvert.DeserializeObject(json);

// await context.PostAsync(dictObj.Keys());

findJsonValues(Elements)


 private Dictionary&lt;string, string&gt; findJsonValues(JObject Cat)
    {

        foreach (var pair in Cat)
        {
            string sKey = pair.Key;
            // string ln = pair.Value.ToString();
            string ss = Cat[sKey].ToString();
            if (ss.StartsWith(&quot;https&quot;))
            {
                //Add the catalogue and link to this dictionary to create final card
                Console.WriteLine(&quot;Hey&quot;);
                Link = ss;
                //return Link;
                // Cat = null;
                //  break;
                

                linkDictionary.Add(sKey,ss);
                jsonIntentLimit++;
                if (jsonIntentLimit == 3)
                {
                    //call a function
                }
                continue;
            }

           
            jsonValues(context,(JObject)pair.Value);
        }
     
        

    }

Please Help.

答案1

得分: 2

使用此函数递归迭代所有节点

private static void Iterate(JToken token, Dictionary<string, string> keyValuePairs)
{
    if (token is JProperty && token.First is JValue)
    {
        if (!keyValuePairs.ContainsKey(((JProperty)token).Name))
            keyValuePairs.Add(((JProperty)token).Name, ((JProperty)token).Value.ToString());
    }

    foreach (JToken token2 in token.Children())
        Iterate(token2, keyValuePairs);
}

调用此方法以获取所有节点

using (StreamReader r = new StreamReader(filepath))
{
    string json = r.ReadToEnd();
    JToken token = JToken.Parse(json);
    var keyValuePairs = new Dictionary<string, string>();
    Iterate(token, keyValuePairs);

    foreach (var keyValue in keyValuePairs)
    {
        Console.WriteLine($"{keyValue.Key}:{keyValue.Value}");
    }
}
英文:

Use this fucntion to iterate all nodes recursively

private static void Iterate(JToken token, Dictionary&lt;string, string&gt; keyValuePairs)
{
    if (token is JProperty &amp;&amp; token.First is JValue)
    {
        if (!keyValuePairs.ContainsKey(((JProperty)token).Name))
            keyValuePairs.Add(((JProperty)token).Name, ((JProperty)token).Value.ToString());
    }

    foreach (JToken token2 in token.Children())
        Iterate(token2, keyValuePairs);
}

call this method to get all nodes

using (StreamReader r = new StreamReader(filepath))
{
    string json = r.ReadToEnd();
    JToken token = JToken.Parse(json);
    var keyValuePairs = new Dictionary&lt;string, string&gt;();
    Iterate(token, keyValuePairs);

    foreach (var keyValue in keyValuePairs)
    {
        Console.WriteLine($&quot;{keyValue.Key}:{keyValue.Value}&quot;);
    }
}

huangapple
  • 本文由 发表于 2020年1月6日 22:19:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定