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

时间:2014-08-14 12:27:56

标签: c# .net json

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

这是我的JSON字符串:

{
  "424406": true,
  "425171": true,
  "411961": true
}

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

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

foreach (dynamic x in dynObj)
{
   string Id = ????
   bool boolValue = ???
}

如何获得" x"中的每个对象?没有指定名称?

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

List<string,bool>

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

1 个答案:

答案 0 :(得分: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);
        }
    }
}

该值的强制转换是从JTokenbool调用explicit conversion。这里根本不需要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);
        }
    }
}

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