反序列化字符串化的JSON对象

dev*_*ead 2 .net c# json

我已经阅读了一些关于如何执行此操作的帖子,但是我看到JSON对象的所有内容都有要查询的特定属性名称,我不这样做.

这是我的JSON字符串:

{
  "424406": true,
  "425171": true,
  "411961": true
}
Run Code Online (Sandbox Code Playgroud)

我想循环遍历数组并单独读取字符串和bool字段(JSON字符串存储在隐藏变量中,然后在我的asp.net代码中访问):

dynamic dynObj = JsonConvert.DeserializeObject(partDetailsSelectedItems.Value);

foreach (dynamic x in dynObj)
{
   string Id = ????
   bool boolValue = ???
}
Run Code Online (Sandbox Code Playgroud)

如何在不指定名称的情况下获取"x"中的每个对象?

理想情况下,我想将这个字符串化的JSON转换为通用列表

List<string,bool>
Run Code Online (Sandbox Code Playgroud)

但我需要了解如何处理我的上述情况.

Jon*_*eet 6

如果你使用LINQ to JSON它很简单,因为JObject你可以迭代所有的键/值对 - 它实现了IEnumerable<KeyValuePair<string, JToken>>:

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

class Test
{
    public static void Main(string[] args)
    {
        string text = File.ReadAllText("test.json");
        var json = JObject.Parse(text);

        foreach (var pair in json)
        {
            string id = pair.Key;
            bool value = (bool) pair.Value;
            Console.WriteLine("id: {0}; value: {1}", id, value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该值中投调用显式转换从JToken到bool.dynamic根本不需要.

或者,如评论中所述,您可以反序列化为Dictionary<string, bool>:

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Test
{
    public static void Main(string[] args)
    {
        string text = File.ReadAllText("test.json");
        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, bool>>(text);

        foreach (var pair in dictionary)
        {
            string id = pair.Key;
            bool value = pair.Value;
            Console.WriteLine("id: {0}; value: {1}", id, value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我自己通常最终会使用LINQ to JSON,但这两种方法都有效,哪种更好取决于您的上下文.

  • 这个答案的第二部分实际上是我原来的答案(很差)试图进入....反序列化为字典而不是"动态".没有必要重新编辑它来重复相同的代码. (2认同)