Azure 函数中的 Http 触发器 - 在驼峰式中序列化对象

Http triggers in azure functions - serializing objects in camelcase

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

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

上面的代码给了我大写字母。 下面的代码给我一个错误 stacktrace

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)

您可以在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;

将 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; }

如果您不返回匿名 classes,您也​​可以使用 Newtonsoft 的 JsonObjectAttribute 来配置 Newtonsoft Json 使用的命名策略。这样做的好处是它适用于序列化 反序列化。

示例class:

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);

class 同样可用于将对象序列化和反序列化为 BrokeredMessage 对象中的 Azure 服务总线负载。比 XML 更少的开销(存在最大消息大小限制),并且在使用服务总线资源管理器解决问题而不是二进制时可读。