这是我的天蓝色功能应用程序。
#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#有JsonArray
,JsonObject
或JsonValue
课程,但我不了解如何使用它们,也不知道它们之间的区别。
答案 0 :(得分:2)
如果你使它有效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]
}
});
答案 1 :(得分:0)
您只需返回一个实例数组,框架将负责转换为JSON。
首先,您创建一个类来保存您的项目:
public class Result
{
public string Name {get; set;}
public int Num {get; set;}
}
现在你只返回一些数组:
return req.CreateResponse(HttpStatusCode.OK, new Result[] {
new Result() {
Name = nameRead[0],
Num = numRead[0]
},
new Result() {
Name = nameRead[1],
Num = numRead[1]
},
new Result() {
Name = nameRead[2],
Num = numRead[2]
}
});
如果您想要更好地控制数据的返回方式,请检查Newtonsoft.JSON
库,它实际上是C#中的默认库,并提供您提到的所有类。它的文档非常好,有很多例子,所以你应该能够在那里找到你需要的东西。