简体   繁体   English

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

[英]Http triggers in azure functions - serializing objects in camelcase

I have created an HttpTriggered azure function that returns a response in capital case. 我创建了一个HttpTriggered azure函数,该函数以大写形式返回响应。 How do I convert it to camel case? 如何将其转换为驼峰式?

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

The above code gives me capital case. 上面的代码使我大写。 The code below gives me an error 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");

Stack trace 堆栈跟踪

    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)

You can use the HttpConfiguration parameter in CreateResponse function as follows 您可以在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);

You are going to add below using statements 您将在以下using语句中添加

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

You can also use Newtonsoft's JsonObjectAttribute if you're not returning anonymous classes, to configure the naming strategy that Newtonsoft Json uses. 如果您不返回匿名类,还可以使用Newtonsoft的JsonObjectAttribute来配置Newtonsoft Json使用的命名策略。 The benefit of this is that it works to both serialise and deserialise. 这样做的好处是它既可以序列化也可以反序列化。

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

Then in your HTTP trigger, or anything else that uses the Newtonsoft to serialise (ie, won't work with Microsoft's DataContract serialiser): 然后在您的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);

The class can be used equally well to serialise and deseralise objects as Azure Service Bus payloads within the BrokeredMessage object. 该类可以很好地用于序列化和反序列化对象,作为BrokeredMessage对象中的Azure Service Bus有效负载。 Less overhead than XML (there's maximum message size limits), and human readable when using the Service Bus Explorer to solve problems as opposed to binary. 比XML少的开销(有最大的消息大小限制),并且在使用Service Bus Explorer来解决问题而不是二进制文件时易于阅读。

Add the JsonPropertyAttribute to the properties and include Json.NET via #r "Newtonsoft.Json" at the top of the file. 将JsonPropertyAttribute添加到属性中,并通过文件顶部的#r“ Newtonsoft.Json”包含Json.NET。

#r "Newtonsoft.Json"

using Newtonsoft.Json;

And decorate the properties 并装饰属性

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM