C#实体对象集合转换为json格式转换⼯具类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;
using System.IO;
namespace WindowsFormsApp3
{
class JsonHelper
{
public static string ListToJson<T>(List<T> list)
{
StringBuilder jsonBuilder =new StringBuilder();
jsonBuilder.Append("[");
for(int i =0, len = list.Count; i < len; i++)
{
DataContractJsonSerializer ser =new DataContractJsonSerializer(typeof(T));
MemoryStream ms =new MemoryStream();
ser.WriteObject(ms, list[i]);
StreamReader reader =new StreamReader(ms);
ms.Position =0;
string str = reader.ReadToEnd();
reader.Close();
jsonBuilder.Append(str);
jsonBuilder.Append(",");
}
jsonBuilder.Remove(jsonBuilder.Length-1,1);
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}
}
}
实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp3
{
[DataContract, Serializable]
public class User
{
[DataMember]
public int id {get;set;}
[DataMember]
public string username {get;set;}
json转换对象[DataMember]
public string pwd {get;set;}
[DataMember]
public int auth {get;set;}
public User(){}
public User(int id,string username,string pwd,int auth)
{
this.id = id;
this.username = username;
this.pwd = pwd;
this.auth = auth;
}
}
}
窗体
private void button2_Click(object sender, EventArgs e)
{
//JsonHelper.ListToJson<User>();
MessageBox.Show(JsonHelper.ListToJson<User>(UserList()));
}
private List<User>UserList(){
List<User> userList =new List<User>();
User user =null;
string sql ="select * from user_table";
SqlCommand cmd = SqlUtils.ConnectSql(sql);
SqlDataReader sdr = cmd.ExecuteReader();
while(sdr.Read())
{
user =new User(sdr.GetInt32(0), sdr.GetString(1), sdr.GetString(2), sdr.GetInt32(3)); userList.Add(user);
}
return userList;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论