我有以下代码,效果很好:
Dim dept As New ArrayList
Dim forename As New ArrayList
objJSONStringBuilder = New StringBuilder()
objSQLConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString"))
objSQLCommand = New SqlCommand("select dept, forename from table1", objSQLConnection)
objSQLCommand.Connection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()
While objSQLDataReader.Read()
dept.Add(New With {Key .dept = objSQLDataReader("dept")})
forename.Add(New With {Key .forename = objSQLDataReader("forename")})
End While
objSQLDataReader.Close()
objSQLCommand.Connection.Close()
Dim serializer As New JavaScriptSerializer()
Dim arrayJson As String = serializer.Serialize(dept)
Return arrayJson
这给了我:
[
{
"dept": "dept1"
},
{
"dept": "dept2"
},
{
"dept": "dept3"
}
]
如何在json数据中添加第二列forename
,以便它返回:
[
{
"dept": "dept1",
"forename": "adam"
},
{
"dept": "dept2",
"forename": "joe"
},
{
"dept": "dept3",
"forename": "smith"
}
]
最终,我想添加更多列,即姓氏。
答案 0 :(得分:4)
您需要创建一个具有两个属性的对象:
dept.Add(New With {Key .dept = objSQLDataReader("dept"), .forename = objSQLDataReader("forename")})
答案 1 :(得分:0)
为什么要将同一个表/对象的dept和forename存储在不同的列表中?我认为你可以采用的最佳方法是创建一个代表'table1'的对象:
public class Table1Object {
public string Dept { get; set; }
public string Forename { get; set; }
}
然后在你的循环中通过数据阅读器这样做:
List<Table1Object> table1List = new List<Table1Object>()
while (objSQLDataReader.Read())
{
table1List.Add(new Table1Object
{
Dept = objSQLDataReader("dept"),
Forename = objSQLDataReader("forename")
});
}
之后
string arrayJson = serializer.Serialize(table1List)
应该给你想要的json
PS。我的VB有点生疏,但是如果我在代码中犯了任何错误,我希望你能得到它的主旨:)