相关疑难解决方法(0)

将字典序列化为数组(键值对)

Json.Net通常将a序列Dictionary<k,v>化为集合;

"MyDict": {
  "Apples": {
    "Taste": 1341181398,
    "Title": "Granny Smith",
  },
  "Oranges": {
    "Taste": 9999999999,
    "Title": "Coxes Pippin",
  },
 }
Run Code Online (Sandbox Code Playgroud)

哪个好.从环顾四周看似乎是大多数人想要的东西.但是,在这种特殊情况下,我想在我的Dictionary<k,v>和Array格式之间进行序列化;

"MyDict": [
    "k": "Apples",
    "v": {
        "Taste": 1341181398,
        "Title": "Granny Smith",
    }
  },
    "k:": "Oranges",
    "v:": {
        "Taste": 9999999999,
        "Title": "Coxes Pippin",
    }
  },
]
Run Code Online (Sandbox Code Playgroud)

使用我现有的字段类型有一种简单的方法吗?有没有我可以注释的属性?

c# json.net

32
推荐指数
4
解决办法
4万
查看次数

如何使用Json.Net使用自定义键序列化/反序列化字典?

我有以下类,我用作字典中的键:

    public class MyClass
    {
        private readonly string _property;

        public MyClass(string property)
        {
            _property = property;
        }

        public string Property
        {
            get { return _property; }
        }

        public override bool Equals(object obj)
        {
            MyClass other = obj as MyClass;
            if (other == null) return false;
            return _property == other._property;
        }

        public override int GetHashCode()
        {
            return _property.GetHashCode();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我正在运行的测试在这里:

    [Test]
    public void SerializeDictionaryWithCustomKeys()
    {
        IDictionary<MyClass, object> expected = new Dictionary<MyClass, object>();
        expected.Add(new MyClass("sth"), 5.2);
        JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings …
Run Code Online (Sandbox Code Playgroud)

.net c# json json.net

7
推荐指数
3
解决办法
1万
查看次数

标签 统计

c# ×2

json.net ×2

.net ×1

json ×1