1

I have created an HttpTriggered azure function that returns a response in capital case. 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)
horatius
  • 784
  • 1
  • 12
  • 30

3 Answers3

4

You can use the HttpConfiguration parameter in CreateResponse function as follows

        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 Newtonsoft.Json.Serialization;
using System.Web.Http;
2

You can also use Newtonsoft's JsonObjectAttribute if you're not returning anonymous classes, to configure the naming strategy that Newtonsoft Json uses. 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):

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. 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.

0

Add the JsonPropertyAttribute to the properties and include Json.NET via #r "Newtonsoft.Json" at the top of the file.

#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; }
hjgraca
  • 1,695
  • 1
  • 14
  • 29