簡體   English   中英

為什么這個 azure function 會產生 JSON Z78E6221F6393D1356681DBCE39?

[英]Why does this azure function produce a JSON output?

I am following a tutorial for creating an Azure app, part of which cleans up the html from the body of an email: https://docs.microsoft.com/en-us/azure/logic-apps/tutorial-process-email -attachments-workflow#create-function-to-clean-html

相關部分如下:

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log) {

   log.LogInformation("HttpWebhook triggered");

   // Parse query parameter
   string emailBodyContent = await new StreamReader(req.Body).ReadToEndAsync();

   // Replace HTML with other characters
   string updatedBody = Regex.Replace(emailBodyContent, "<.*?>", string.Empty);
   updatedBody = updatedBody.Replace("\\r\\n", " ");
   updatedBody = updatedBody.Replace(@"&nbsp;", " ");

   // Return cleaned text
   return (ActionResult)new OkObjectResult(new { updatedBody });
}

以下測試輸入: {"name": "<p><p>Testing my function</br></p></p>"}

預計會給出如下 output: {"updatedBody":"{\"name\": \"Testing my function\"}"}

為什么 output 包裹在 {"updatedBody":} json 中?

從代碼中我可以看出,output 是作為字符串數組提供的,使用名為 updatedBody 的 object 填充數組中的唯一元素( return (ActionResult)new OkObjectResult(new { updatedBody }); ) -但看起來{ updatedBody }以某種方式被視為 json 數組?

object OkObjectResult That class is responsible (along with the underlying azure function / asp.net core pipeline) for serializing that data into a string, and adding it to the HTTP response content. (有一些特殊情況,比如你傳入的數據是一個string ,但現在不重要了)

方法結束為您完成序列化。 你不必擔心它。 框架會處理它。

這就是為什么您的 JSON 具有包裝的“updatedBody”屬性的原因。 如果我有以下代碼:

string myValue = "yes";
return OkObjectResult(new {
  myValue
});

我會得到以下 JSON

{
  "myValue": "yes"
}

您也可以更改屬性名稱

string myValue = "yes";
return OkObjectResult(new {
  message = myValue
});
{
  "message": "yes"
}

這就是 JSON.Net(c# 庫)和 Microsoft 的 System.Text.Json 庫的工作原理,OkObjectResult 在幕后使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM