gpt4 book ai didi

c# - Azure Function 返回多个 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 21:34:14 24 4
gpt4 key购买 nike

这是我的 azure 函数应用程序。

#r "System.Configuration"
#r "System.Data"
using System.Net;
using System.Configuration;
using System.Data.SqlClient;
using System.Threading.Tasks;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req,
TraceWriter log)
{
int num;
string query = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "num", true) == 0)
.Value;

if (query == null)
{
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
num = data.num;
}
else {
num = Convert.ToInt32(query);
}

int[] numRead = new int[3];
string[] nameRead = new string[3];

var str =
ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString;

using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
var text = "select num,name from bus where num=@num;";

using (SqlCommand cmd = new SqlCommand(text, conn))
{
cmd.Parameters.AddWithValue("@num", num);
using (SqlDataReader reader = cmd.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
numRead[i] = reader.GetInt32(0);
nameRead[i++] = reader.GetString(1);
Console.WriteLine(numRead[i] + ":" + nameRead[i]);
}
}
}
}
return req.CreateResponse(HttpStatusCode.OK, new {
name = nameRead[0],
num = numRead[0]
});
}

我希望函数像这样返回多个 json

return req.CreateResponse(HttpStatusCode.OK, new {
"item1" : {
name = nameRead[0],
num = numRead[0]
},
"item2" : {
name = nameRead[1],
num = numRead[1]
},
"item3" : {
name = nameRead[2],
num = numRead[2]
}
});

但它不起作用。

C# 有 JsonArrayJsonObjectJsonValue 类,但我不明白如何使用它们,也不知道它们之间的区别他们之间。

最佳答案

如果你让它有效的 C# 它应该可以工作:

return req.CreateResponse(HttpStatusCode.OK, new {
item1 = new {
name = nameRead[0],
num = numRead[0]
},
item2 = new {
name = nameRead[1],
num = numRead[1]
},
item3 = new {
name = nameRead[2],
num = numRead[2]
}
});

关于c# - Azure Function 返回多个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50487015/

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