【问题标题】:Newtonsoft json Serialize Primitive types WebApiNewtonsoft json 序列化原始类型 WebApi
【发布时间】:2013-11-07 15:38:18
【问题描述】:

我有一个使用 C# 的 Web API 项目,我正在尝试将 Json 序列化程序 (Newtonsoft JSON) 配置为始终返回包装响应,因为当我的 api 控制器仅返回布尔值或整数(或其他原始类型)时,我只是得到对象,但我想要类似的东西:

{ d : true } 

一个包装的结果,但没有修改控制器,我看到有很多配置的东西:

config.Formatters.JsonFormatter.SerializerSettings

但我没有找到提供这种行为的那个。

谢谢!

【问题讨论】:

  • 你现在得到了什么?
  • 只是“真实”或数字
  • 有人吗? OP有没有解决这个问题?例如。返回小数点 0.54 就是这样,而不是像 { "Result": 0.54 } 这样的包装响应

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


【解决方案1】:

嗨,我终于解决了创建自己的继承自 JsonMediaTypeFormatter 的 Formatter,如下所示:

config.Formatters.Add(new WrappedJsonMediaTypeFormatter());

public class WrappedJsonMediaTypeFormatter : JsonMediaTypeFormatter
{

        public WrappedJsonMediaTypeFormatter() 
        {
            base.SerializerSettings.Culture = new System.Globalization.CultureInfo("en-GB");
            base.SerializerSettings.DateFormatString = "dd/MM/yyyy";
        }

        public override System.Threading.Tasks.Task WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
        {
            var obj = value;
            if (type.IsPrimitive || Object.ReferenceEquals(type, typeof(string)))
                obj = new { data = value };

            if (Object.ReferenceEquals(value, null))
                obj = new { };

            return base.WriteToStreamAsync(type, obj, writeStream, content, transportContext);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2013-06-06
    • 1970-01-01
    相关资源
    最近更新 更多