JSON.NET序列化为没有属性名称的特定JSON格式



我正在尝试为Tinymce SpellChecker编写自定义实现。我需要从我的ASHX页面返回格式的JSON对象

{
  "words": {
     "misspelled1": ["suggestion1", "suggestion2"],
     "misspelled2": ["suggestion1", "suggestion2"]
  }
}

拼写错误的1和2是拼写错误的单词及其各自的建议,词是ID,因此一个实用的例子是

{words:{
"wod":["wood","wooden"],
"tak":["take","taken"]}
}

我尝试了这个

public class incorrectWords
{
    public string word { get; set; }
    public string[] suggestions { get; set; }
}
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new
        {
            words= new List<incorrectWords>()
                    {
                        new words {word="wod",suggestions = new string[]{ "wood","wooden" } },
                        new words  {word="tak",suggestions= new string[]{ "talk","take" } }
        }
        });
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(json,Newtonsoft.Json.Formatting.Indented));
    }

但是,添加了属性名称单词和建议,我最终得到了以下内容,这不是我需要的。

"{"words":[{"word":"wod","suggestions":["wood","wooden"]},{"word":"tak","suggestions":["talk","take"]}]}"

事先感谢您的任何指示。一些帖子似乎表明我需要一个自定义的转换器,我想知道这是否是设计不正确的类

的简单问题。

如果您想在JSON中具有键值对,则应将您的列表映射到字典。
这是您的代码的修改版本,它有效:

var words = new List<incorrectWords>() {
            new incorrectWords() {word="wod",suggestions = new string[]{ "wood","wooden" } },
            new incorrectWords() {word="tak",suggestions= new string[]{ "talk","take" } }
};
var dic = new Dictionary<string, string[]>();
words.ForEach(word =>
{
    dic.Add(word.word, word.suggestions);
});
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new {
    words = dic
});
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(json, Newtonsoft.Json.Formatting.Indented));

相关内容

  • 没有找到相关文章

最新更新