2016-08-14 103 views
11

我在使用Azure Functions。但是,我覺得我很難找到一些非常簡單的東西。我試圖找出如何返回一些基本的JSON。我不確定如何創建一些JSON並將其恢復到我的請求。如何從Azure功能返回JSON

曾幾何時,我會創建一個對象,填充它的屬性並序列化它。於是,我開始了這條路:

#r "Newtonsoft.Json" 

using System.Net; 

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) 
{ 
    log.Info($"Running Function");  
    try {  
     log.Info($"Function ran"); 

     var myJSON = GetJson(); 

     // I want myJSON to look like: 
     // { 
     // firstName:'John', 
     // lastName: 'Doe', 
     // orders: [ 
     //  { id:1, description:'...' }, 
     //  ... 
     // ] 
     // } 
     return ?; 
    } catch (Exception ex) { 
     // TODO: Return/log exception 
     return null; 
    } 
} 

public static ? GetJson() 
{ 
    var person = new Person(); 
    person.FirstName = "John"; 
    person.LastName = "Doe"; 

    person.Orders = new List<Order>(); 
    person.Orders.Add(new Order() { Id=1, Description="..." }); 

    ? 
} 

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public List<Order> Orders { get; set; } 
} 

public class Order 
{ 
    public int Id { get; set; } 
    public string Description { get; set; } 
} 

不過,我完全被困在序列化和返回過程now.I猜我已經習慣了在ASP.NET MVC返回JSON這裏的一切是動作

+0

你有一些答案 - 請標明一個作爲回答你的問題。我根據最近的文檔提供了最新的答案。 –

回答

4

JSON很簡單,Newtonsoft.Json庫是一個special case。您可以通過在腳本文件的頂部添加此包括它:

#r "Newtonsoft.Json" 

using Newtonsoft.Json; 

那麼你的函數變爲:

public static string GetJson() 
{ 
    var person = new Person(); 
    person.FirstName = "John"; 
    person.LastName = "Doe"; 

    person.Orders = new List<Order>(); 
    person.Orders.Add(new Order() { Id=1, Description="..." }); 

    return JsonConvert.SerializeObject(person); 
} 
+1

但是,如何從'Run'方法返回? 'Run'方法返回一個不是字符串的'HttpResponseMessage'。但是,我不想返回一個原始字符串。相反,我想返回JSON。 –

+0

一種方法就是手動創建一個HttpResponseMessage。將它的內容設置爲Json的StringContent。 – juunas

+0

你可以在這裏看到一個例子:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results – juunas

2

您可以更改方法簽名爲:

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log) 

和它將允許返回JSON數據。

+2

剛剛在Azure門戶上嘗試過,並且幫助我返回JSON:'return req.CreateResponse(HttpStatusCode.OK,result,「application/json」);',無需使用方法簽名 –

0

我有一個類似的問題,這似乎是最流行的職位,沒有答案。在弄清楚下面哪個節點應該工作後,給出你到底是什麼。其他示例仍會返回一個字符串表示形式,它將返回JSON。

記得使用System.Text聲明;並且還根據Juunas響應向GetJson函數添加:

return JsonConvert.SerializeObject(person); 

return new HttpResponseMessage(HttpStatusCode.OK) 
 
     { 
 
      Content = new StringContent(GetJson(), Encoding.UTF8, "application/json") 
 
     };

13

這裏有蔚藍的函數返回一個格式正確的JSON對象而不是XML的一個完整的例子:在瀏覽器中

#r "Newtonsoft.Json" 
using System.Net; 
using Newtonsoft.Json; 
using System.Text; 

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) 
{ 
    var myObj = new {name = "thomas", location = "Denver"}; 
    var jsonToReturn = JsonConvert.SerializeObject(myObj); 

    return new HttpResponseMessage(HttpStatusCode.OK) { 
     Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json") 
    }; 
} 

導航到終點,你會看到:

{ 
    "name": "thomas", 
    "location": "Denver" 
} 
4

您可以拿req

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) 

,並創建在裝配System.Web.Http使用

return req.CreateResponse(HttpStatusCode.OK, json, "application/json"); 

或任何其他重載的響應。

更多信息上docs.microsoft.com

+1

我更喜歡使用:' req.CreateResponse(HttpStatusCode.OK,json,JsonMediaTypeFormatter.DefaultMediaType);'。我認爲它比'application/json'字符串更安全。 – DoronG

1

看起來這可以通過使用「應用/ JSON的」媒體類型剛剛實現,而無需顯式序列化PersonNewtonsoft.Json

下面是在Chrome結果作爲完整的工作示例:

{"FirstName":"John","LastName":"Doe","Orders":[{"Id":1,"Description":"..."}]} 

的代碼給出如下:

[FunctionName("StackOverflowReturnJson")] 
    public static HttpResponseMessage Run([HttpTrigger("get", "post", Route = "StackOverflowReturnJson")]HttpRequestMessage req, TraceWriter log) 
    { 
     log.Info($"Running Function"); 
     try 
     { 
      log.Info($"Function ran"); 

      var myJSON = GetJson(); // Note: this actually returns an instance of 'Person' 

      // I want myJSON to look like: 
      // { 
      // firstName:'John', 
      // lastName: 'Doe', 
      // orders: [ 
      //  { id:1, description:'...' }, 
      //  ... 
      // ] 
      // } 
      var response = req.CreateResponse(HttpStatusCode.OK, myJSON, JsonMediaTypeFormatter.DefaultMediaType); // DefaultMediaType = "application/json" does the 'trick' 
      return response; 
     } 
     catch (Exception ex) 
     { 
      // TODO: Return/log exception 
      return null; 
     } 
    } 

    public static Person GetJson() 
    { 
     var person = new Person(); 
     person.FirstName = "John"; 
     person.LastName = "Doe"; 

     person.Orders = new List<Order>(); 
     person.Orders.Add(new Order() { Id = 1, Description = "..." }); 

     return person; 
    } 

    public class Person 
    { 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public List<Order> Orders { get; set; } 
    } 

    public class Order 
    { 
     public int Id { get; set; } 
     public string Description { get; set; } 
    }