按照惯例 先添加命名空间
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Runtime.Serialization;
如果报错需添加类库引用
定义json class类
[DataContract]
public class stuent
{
private string _name;
private int _number;
[DataMember]
public string name
{
get { return _name; }
set { _name = value; }
}
[DataMember]
public int number
{
get { return _number; }
set { _number = value; }
}
}
public class stuent
{
private string _name;
private int _number;
[DataMember]
public string name
{
get { return _name; }
set { _name = value; }
}
[DataMember]
public int number
{
get { return _number; }
set { _number = value; }
}
}
main函数中/或其他地方引用
{//先定义对象
stuent student
test = new stuent();
stuent.number= 1
;
stuent.name= “xiaoming
“;
test = new stuent();
stuent.number= 1
;
stuent.name= “xiaoming
“;
stuent studenttest1= new stuent ();
studenttest1.number= 2
;
studenttest1.name= “daming
“;
studenttest1.number= 2
;
studenttest1.name= “daming
“;
//定义列表
List<stuent > stuents= new List<stuent >();
stuents.Add(studenttest );
stuents.Add(studenttest1);
stuents.Add(studenttest );
stuents.Add(studenttest1);
DataContractJsonSerializer json = new DataContractJsonSerializer(stuents.GetType());
string szJson = “”;
//序列化
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, stuents);
Json = Encoding.UTF8.GetString(stream.ToArray());
}
string szJson = “”;
//序列化
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, stuents);
Json = Encoding.UTF8.GetString(stream.ToArray());
}
Console.WriteLine(Json);
Console.ReadLine();
Console.ReadLine();
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/10965.html