gpt4 book ai didi

c# - 如何从azure函数c#返回多个json对象?

转载 作者:行者123 更新时间:2023-12-02 07:46:37 26 4
gpt4 key购买 nike

我已经检查了重复的问题并尝试了相同的代码,但不起作用。

我有两个 json 序列化对象,想要返回这两个输出。

#r "Newtonsoft.Json"

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

public static async Task<HttpResponseMessage> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);

var httpResult = data.a;
var sqlData = data.b;

var matchedList = new List<dynamic>();

var unmatchedList = new List<dynamic>();


foreach (var itemHttp in httpResult)
{
foreach (var itemSql in sqlData)
{
if (itemHttp.name == itemSql.tablename)
{
matchedList.Add(itemHttp);
}
else{

unmatchedList.Add(itemHttp.name);
}
}
}

var jsonToReturn1 = JsonConvert.SerializeObject(matchedList);

var jsonToReturn2 = JsonConvert.SerializeObject(unmatchedList);


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


}

用于函数的输入 -

{
"a": [
{
"id": "1",
"name": "aaa"
},
{
"id": "2",
"name": "bbb"
},
{
"id": "3",
"name": "ccc"
},
{
"id": "4",
"name": "ddd"
}
],
"b": [
{
"id": "111",
"tablename": "aaa"
},
{
"id": "222",
"tablename": "bbb"
}
]
}

最佳答案

有两种方法:

第一个(更可取)

public static async Task<HttpResponseMessage> Run(HttpRequest req, ILogger log)
{
dynamic data = await req.Content.ReadAsAsync<object>();

// ..

var result = new
{
a = matchedList,
b = unmatchedList
};

/* The mediaType-param with value 'JsonMediaTypeFormatter.DefaultMediaType' can be omitted. */
return req.CreateResponse(HttpStatusCode.OK, result, JsonMediaTypeFormatter.DefaultMediaType);
}

第二个

public static async Task<HttpResponseMessage> Run(HttpRequest req, ILogger log)
{
dynamic data = await req.Content.ReadAsAsync<object>();

// ..

var payload = JsonConvert.SerializeObject(new
{
a = matchedList,
b = unmatchedList
});

var content = new StringContent(payload, Encoding.UTF8, "application/json");

return new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
}

关于c# - 如何从azure函数c#返回多个json对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57127316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com