来自数据表的嵌套json
本文关键字:嵌套 json 数据表 | 更新日期: 2023-09-27 18:05:44
我有一个数据表的值:
UerId TimeStamp Parameter Value
----- --------- --------- -----
1 03/24/2013 Param1 Value1
1 03/24/2013 Param2 Value2
1 03/24/2013 Param3 Value3
1 03/25/2013 Param4 Value4
1 03/25/2013 Param5 Value5
2 03/24/2013 Param1 Value6
2 03/24/2013 Param2 Value7
2 03/25/2013 Param1 Value8
我需要创建嵌套json字符串,如:
Users:[
"UserId": <id>,
"date":[
"TimeStamp": <TimeStamp>,
"Values" : [
{ "Parameter": <Parameter>, "Value": <Value> },
{ "Parameter": <Parameter>, "Value": <Value> },
...
]
],
...
]
I made distinct list of values:
List<String> ListOfUsers = new List<String>();
List<DateTime> ListOfDates = new List<DateTime>();
ListOfUsers = dt.AsEnumerable().Select(row => row.Field<String>("UserId")).Distinct().ToList<String>();
ListOfDates = dt.AsEnumerable().Select(row => row.Field<DateTime>("TimeStamp").Date).Distinct().ToList<DateTime>();
我应该循环通过整个表或有任何其他更好的方式,也许与Json.net库?谢谢。
您可以通过多种方式做到这一点,但最简单的是通过使用。net JavaScriptSerializer。只需构建类来模拟您感兴趣的结构,用数据库中的数据填充对象,然后对其进行序列化。我给你举个例子。
使用this作为要填充的对象
public class YourObject
{
public YourObject(){
}
public YourObject (DataTable dataTable){
//Do work here to load your data set into your Users and other necessary objects.
Users = new Users(dataTable);
}
public UsersObject Users { get; set; }
public class UsersObject : List<UserObject> {
public UsersObject (DataTable dataTable){
dataTable.AsEnumerable().Select(row => row.Field<String>("UserId")).Distinct().ToList<String>().ForEach(x => this.Add(new UserObject(){UserId = x}));
foreach(UserObject user in this){
user.LoadDates(dataTable.Select("UserId = '" + user.UserId + "'"));
}
}
}
public class UserObject {
public UserObject (){
date = new DatesObject();
}
public void LoadDates(DataRow[] rows){
rows.AsEnumerable().Select(row => row.Field<DateTime>("TimeStamp").Date).Distinct().ToList<DateTime>().ForEach(x => this.Add(new DateObject(){TimeStamp = x}));
foreach(DateObject date in this){
date.LoadParams(rows.Select("TimeStamp = '" + date.TimeStamp.ToString("MM/dd/yyyy") + "'"));
}
}
public string UserId { get; set; }
public DatesObject date { get; set; }
}
public class DatesObject : List<DateObject>{
public DatesObject (){
}
}
public class DateObject {
public DateObject () {
}
public void LoadValues(DataRow[] rows){
//Load your value/params like in the previous methods
}
public DateTime TimeStamp { get; set; }
public ValuesObject Values { get; set; }
}
public class ValuesOject : List<ValueObject> {
public ValuesOject () {
}
}
public class ValueObject {
public ValueObject () {
}
public string Parameter { get; set; }
public string Value { get; set; }
}
}
然后使用this来序列化该对象
protected void Page_Load(object sender, EventArgs e){
YourObject yourObject = new YourObject(Data.GetYourDataTable());
JavaScriptSerializer serializer = new JavaScriptSerializer();
string serializedItems = serializer.Serialize(yourObject);
}