【问题标题】:Http triggers in azure functions - serializing objects in camelcase天蓝色函数中的 Http 触发器 - 以驼峰形式序列化对象
【发布时间】:2018-02-06 08:05:09
【问题描述】:

我创建了一个 HttpTriggered azure 函数,它以大写形式返回响应。如何将其转换为驼峰式?

    return feedItems != null
            ? req.CreateResponse(HttpStatusCode.OK, feedItems
            : req.CreateErrorResponse(HttpStatusCode.NotFound, "No news articles were found");

上面的代码给了我大写。 下面的代码给了我一个错误堆栈跟踪

return feedItems != null
                    ? req.CreateResponse(
                        HttpStatusCode.OK, 
                        feedItems, 
                        new JsonMediaTypeFormatter
                        {
                            SerializerSettings = new JsonSerializerSettings
                            {
                                Formatting = Formatting.Indented,
                                ContractResolver = new CamelCasePropertyNamesContractResolver()
                            }
                        })
                    : req.CreateErrorResponse(HttpStatusCode.NotFound, "No news articles were found");

堆栈跟踪

    Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: NewsFeedController ---> System.MissingMethodException : Method not found: 'Void System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.set_SerializerSettings(Newtonsoft.Json.JsonSerializerSettings)'.
   at Juna.Zone.NewsFeed.Aggregator.NewsFeedController.Run(HttpRequestMessage req,TraceWriter log)
   at lambda_method(Closure ,NewsFeedController ,Object[] )
   at Microsoft.Azure.WebJobs.Host.Executors.MethodInvokerWithReturnValue`2.InvokeAsync(TReflected instance,Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,ParameterHelper parameterHelper,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??) 
   End of inner exception
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsync(IFunctionInstance functionInstance,CancellationToken cancellationToken)
   at Microsoft.Azure.WebJobs.Host.Executors.ExceptionDispatchInfoDelayedException.Throw()
   at async Microsoft.Azure.WebJobs.JobHost.CallAsync(??)
   at async Microsoft.Azure.WebJobs.Script.ScriptHost.CallAsync(String method,Dictionary`2 arguments,CancellationToken cancellationToken)
   at async Microsoft.Azure.WebJobs.Script.WebHost.WebScriptHostManager.HandleRequestAsync(FunctionDescriptor function,HttpRequestMessage request,CancellationToken cancellationToken)
   at async Microsoft.Azure.WebJobs.Script.Host.FunctionRequestInvoker.ProcessRequestAsync(HttpRequestMessage request,CancellationToken cancellationToken,WebScriptHostManager scriptHostManager,WebHookReceiverManager webHookReceiverManager)
   at async Microsoft.Azure.WebJobs.Script.WebHost.Controllers.FunctionsController.<>c__DisplayClass3_0.<ExecuteAsync>b__0(??)
   at async Microsoft.Azure.WebJobs.Extensions.Http.HttpRequestManager.ProcessRequestAsync(HttpRequestMessage request,Func`3 processRequestHandler,CancellationToken cancellationToken)
   at async Microsoft.Azure.WebJobs.Script.WebHost.Controllers.FunctionsController.ExecuteAsync(HttpControllerContext controllerContext,CancellationToken cancellationToken)
   at async System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
   at async System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
   at async System.Web.Http.Cors.CorsMessageHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
   at async Microsoft.Azure.WebJobs.Script.WebHost.Handlers.WebScriptHostHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
   at async Microsoft.Azure.WebJobs.Script.WebHost.Handlers.SystemTraceHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
   at async System.Web.Http.HttpServer.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)

【问题讨论】:

    标签: c# json.net camelcasing system.web.http


    【解决方案1】:

    您可以在 CreateResponse 函数中使用 HttpConfiguration 参数,如下所示

            HttpConfiguration config = new HttpConfiguration();
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
    
            var response = req.CreateResponse(HttpStatusCode.OK, data, config);
    

    您将在下面添加 using 语句

    using Newtonsoft.Json.Serialization;
    using System.Web.Http;
    

    【讨论】:

      【解决方案2】:

      如果您不返回匿名类,您还可以使用 Newtonsoft 的 JsonObjectAttribute 来配置 Newtonsoft Json 使用的命名策略。这样做的好处是它可以同时序列化反序列化。

      示例类:

      using Newtonsoft.Json;
      using Newtonsoft.Json.Serialization;
      
      [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
      public class FeedItems {
        public string Name { get; set; } = string.Empty;
        public int Quantity { get; set; } = 0;
        public string OtherProperty { get; set; } = string.Empty;
      }
      

      然后在您的 HTTP 触发器或任何其他使用 Newtonsoft 进行序列化的东西中(即,不能使用 Microsoft 的 DataContract 序列化器):

      FeedItems feedItems = new feedItems {
        Name = "Something",
        Quantity = 5,
        OtherProperty = "This only exists to show a property with two capitals"
      };
      
      req.CreateResponse(HttpStatusCode.OK, feedItems);
      

      该类同样可以很好地用于将对象作为 BrokeredMessage 对象中的 Azure 服务总线有效负载进行序列化和反序列化。与 XML 相比开销更少(有最大消息大小限制),并且在使用服务总线资源管理器解决问题(而不是二进制文件)时易于阅读。

      【讨论】:

        【解决方案3】:

        将 JsonPropertyAttribute 添加到属性中,并通过文件顶部的#r "Newtonsoft.Json" 包含 Json.NET。

        #r "Newtonsoft.Json"
        
        using Newtonsoft.Json;
        

        并装饰属性

        [JsonProperty(PropertyName = "name" )]
        public string Name { get; set; }
        
        [JsonProperty(PropertyName = "otherProp" )]
        public string OtherProp { get; set; }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-15
          • 1970-01-01
          • 2018-12-27
          • 2013-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多