本文介绍了Json.Net - 词典序列化作为阵列(键值对的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Json.Net通常一个序列化词典< K,V> 成的集合;

Json.Net typically serializes a Dictionary<k,v> into a collection;

"MyDict": {
  "Apples": {
    "Taste": 1341181398,
    "Title": "Granny Smith",
  },
  "Oranges": {
    "Taste": 9999999999,
    "Title": "Coxes Pippin",
  },
 }

这是伟大的。而从环顾所以这似乎是大多数人想要的。然而,在这种特殊情况下,我想我与词典&LT连载; K,V&GT; 和Array格式代替;

Which is great. And from looking around on SO it seems to be what most people want. However, in this particular case, I want to serialize between my Dictionary<k,v> and the Array format instead;

"MyDict": [
    "k": "Apples",
    "v": {
        "Taste": 1341181398,
        "Title": "Granny Smith",
    }
  },
    "k:": "Oranges",
    "v:": {
        "Taste": 9999999999,
        "Title": "Coxes Pippin",
    }
  },
]

有一个简单的方式与现有的字段类型做到这一点?有没有我可以标注例如属性?

Is there an easy way to do this with my existing field type? Is there an attribute I can annotate for instance?

推荐答案

嗯,事实证明这是我所希望的那么简单。我的词典&LT; K,V&GT; 已经子类,而我发现我可以用将其标注为[JsonArrayAttribute] 。这给了我正是我需要的格式;

Ah, it turns out this is as straightforward as I'd hoped. My Dictionary<k,v> is subclassed already and I found that I can annotate it with [JsonArrayAttribute]. That gives me exactly the format I need;

"MyDict": [
  {
    "Key": "Apples",
    "Value": {
        "Taste": 1341181398,
        "Title": "Granny Smith",
    }
  },
  {
    "Key:": "Oranges",
    "Value:": {
        "Taste": 9999999999,
        "Title": "Coxes Pippin",
    }
  },
]

这篇关于Json.Net - 词典序列化作为阵列(键值对的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:28