【问题标题】:Assigning reader results to multiple objects将阅读器结果分配给多个对象
【发布时间】: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


【解决方案1】:

好吧,让我们试试吧..

var rootNode = new RootObject();
rootNode.name = null;
rootNode.parent = null;
rootNode.children = new List<RootParent>();

using (var connection = new SqlConnection(Common.ConnectionString))
using (var command = new SqlCommand("SELECT ...", connection)) {
    connection.Open();
    using (var reader = command.ExecuteReader()) {
        rootNode.name = (string) reader["COLUMN A"];
        while (reader.Read()) {
            var parentNode = new RootParent();
            parentNode.name = (string) reader["COLUMN B"];
            parentNode.children = new ParentChild[] {
                new ParentChild {
                    name = (string) reader["COLUMN C"],
                    parent = (string) reader["COLUMN B"],
                    children = null
                };
            };
            rootNode.children.Add(parentNode);
        }
    }
}

此实现工作的要求:

public class RootObject {
    public string name;
    public string parent;
    public List<RootParent> children;
}

public class RootParent {
    public string name;
    public List<ParentChild> children;
}

public class ParentChild {
    public string name;
    public string parent;
    public List<object> children;
}

编辑

请注意,您必须返回RootObject root。根据属性参数ResponseFormat = ResponseFormat.Json,响应应该被自动转换/序列化。

你使用什么类型的网络项目来实现你的逻辑?

忘记将parentNode 添加到root 实例。确保添加行rootNode.children.Add(parentNode); ..

更新了上面的部分..

【讨论】:

  • 如果不使用Serialize,那么我不会返回 JSON,而是获取 XML 格式。我正在使用WebForms,并且使用您的代码,我仍然得到与以前相似的结果。我得到了 5 个Root Objects,而我正在寻找的是 1 个带有多个 Child Objects 的 RootObject
  • 我刚刚添加了 rootNode.children.Add(parentNode); 并收到以下错误:Error 2 The best overloaded method match for 'System.Collections.Generic.List&lt;Child&gt;.Add(Child)' has some invalid argumentsError 3 Argument 1: cannot convert from 'RootObject' to 'Child'
  • 好的。以为您将类型用作一些同义词..猜测它们是真实的。那你能不能给我更多的代码。RootObjectChildChild2GrandChild 类型的结构会很棒..
  • 这更有意义,但是我又遇到了错误Error 2 Cannot implicitly convert type 'ParentChild[]' to 'System.Collections.Generic.List&lt;ParentChild&gt;'
  • 您以前是否使用过集合? O.O 只需将数组转换为列表或将类型从ParentChild[] 更改为List&lt;ParentChild&gt;
猜你喜欢
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多