【发布时间】:2015-09-10 09:25:50
【问题描述】:
我正在尝试从数据库中获取数据并将其作为 JSON 返回以用于 Web 服务。我可以毫无问题地返回数据,但似乎只返回第一行的数据,而不是其余的。我正在使用SqlReader,我的代码类似于:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string EvidenceLink()
{
var rootObject = new List<RootObject>();
var root = new RootObject();
string sqlQuery = @"SELECT COLUMN A, COLUMN B, COLUMN C FROM MYTABLE";
using (var connection = new SqlConnection(Common.ConnectionString))
{
using (var cmd = new SqlCommand(sqlQuery, connection))
{
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
root = new RootObject
{
children = new List<Child>
{
new Child
{
name = reader["COLUMN A"].ToString(),
children = new List<Child2>
{
new Child2
{
name = reader["COLUMN B"].ToString(),
parent = reader["COLUMN A"].ToString(),
children = new List<GrandChild>
{
new GrandChild
{
name = reader["COLUMN C"].ToString(),
parent = reader["COLUMN B"].ToString(),
}
}
}
}
}
}
};
root.name = "ParentRoot";
root.parent = "null";
rootObject.Add(root);
}
}
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
var strJSON = js.Serialize(rootObject);
return strJSON;
}
我的数据库中有 5 行,我想要实现的是第一行转到一个 Child Object,另一行转到下一个 Child Object,依此类推。我似乎无法弄清楚为什么它只返回数据库的第一行而不是其余的。
这是我正在尝试制作的JSON
{
"name": "Root",
"parent": "null",
"children": [
{
"name": "First Child",
"children": [
{
"name": "Inner Child",
"parent": "First Child",
"children": null
}
]
},
{
"name": "Second Child",
"children": [
{
"name": "Inner Child",
"parent": "Second Child",
"children": null
}
]
},
{
"name": "Third Child",
"children": [
{
"name": "Inner Child",
"parent": "Third Child",
"children": null
}
]
}
]
}
我的结构如下:
public class GrandChild
{
public string name { get; set; }
public string parent { get; set; }
}
public class Child2
{
public string name { get; set; }
public string parent { get; set; }
public List<GrandChild> children { get; set; }
}
public class Child
{
public string name { get; set; }
public List<Child2> children { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string parent { get; set; }
public List<Child> children { get; set; }
}
提前感谢您的帮助。
【问题讨论】:
-
有什么例外吗?你试过调试代码吗?
-
每次
while循环继续时,您都在创建一个新的根对象.. 只需使用root.children.Add()或其他东西.. 否则每次都会覆盖内容.. -
@JanUnld 你能告诉我你的意思的示例代码sn-p吗
-
读者确定返回所有 5 行吗?
-
@CallumBradbury 是的,我已经调试过了,我可以看到它正在返回数据库的所有 5 行
标签: c# asp.net json web-services