Json.net序列化为没有属性名称的特定json格式

问题描述 投票:1回答:1

我正在尝试为tinymce spellchecker编写自定义实现。我需要一个格式的JSON对象从我的ashx页面返回

{
  "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\"]}]}"

提前感谢任何指针。一些帖子似乎表明我需要一个自定义转换器,我想知道设计错误的Word类是否是一个简单的问题

c# .net json json.net
1个回答
0
投票

如果要在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));
© www.soinside.com 2019 - 2024. All rights reserved.