【问题标题】:Make web api serialize dictionary with the key value as key using data attribute使用数据属性制作以键值为键的web api序列化字典
【发布时间】:2012-05-18 14:52:12
【问题描述】:

我有一个字典,我正在使用 json.net 序列化程序对其进行序列化,它目前正在生成

{"phrases":[{"Key":"my-key1","Value":"blah"},{"Key":"my-key2","Value":"blah2"}]}

但我希望它输出

{"phrases":["my-key1":"blah"},{"my-key2":"blah2"}]}

我的模型看起来像

public class Phrases
{
    public Dictionary<string, string> phrases;
}

是否有可以应用于短语模型的数据属性来导致这种情况发生?

我找到了以下内容,但不想返回字符串 Serialize into a key-value dictionary with Json.Net?

更新:

我正在扩展 web api 控制器,如下所示,如果我使用 JsonConvert.SerializeObject() 我确实得到了正确的序列化,但是我会返回一个字符串。

public class PhraseController : ApiController
    {
        private IApplicationModel applicationModel;

        public Phrases Get(string id)
        {
            var locale = new CultureInfo(id).LCID;
            var phrases = applicationModel.Phrases.Where(x => x.Locale = locale).ToDictionary(x => x.Name, y => y.Value);

            return new Phrases() { phrases = phrases };
        }

        public PhraseController(IApplicationModel applicationModel)
        {
            this.applicationModel = applicationModel;
        }
    }

【问题讨论】:

  • 您使用哪个 json.net 版本?因为"Newtonsoft.Json" version="4.0.8" 产生这个:{"phrases":{"my-key1":"blah","my-key2":"blah2"}} using JsonConvert.SerializeObject(phrases);
  • @nemesv 更新了我的问题
  • 我想知道我的问题是它仍在使用 DataContractJsonSerializer 而不是 json.net

标签: c# asp.net asp.net-mvc-3 json.net asp.net-web-api


【解决方案1】:

我最终设法让它工作。

问题是它仍在使用DataContractJsonSerializer。我在添加 JsonNetFormatter 之前添加了一行删除格式化程序,现在它可以正确序列化。

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);

GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(null));

(我正在使用仍然使用 DataContractJsonSerializer 的 beta 版本)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2021-12-12
    • 2011-10-23
    • 1970-01-01
    相关资源
    最近更新 更多