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

时间:2019-03-13 09:52:51

标签: c# .net json json.net

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

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

其中mispelled1和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\"]}]}"

预先感谢任何指针。有些帖子似乎表明我将需要一个自定义转换器,我想知道设计不正确的Words类是否很简单

1 个答案:

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