1

我创建了一个 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)
4

3 回答 3

4

您可以在 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 Newtonsoft.Json.Serialization;
using System.Web.Http;
于 2018-03-08T03:21:15.677 回答
1

如果您不返回匿名类,您还可以使用 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 相比开销更少(有最大消息大小限制),并且在使用服务总线资源管理器解决问题(而不是二进制)时易于阅读。

于 2018-12-08T09:50:50.120 回答
0

将 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; }
于 2018-09-04T11:21:56.547 回答