当前位置 : 主页 > 网络编程 > net编程 >

.NET object对象与json字符串互转换

来源:互联网 收集:自由互联 发布时间:2023-09-06
一:使用JavaScriptSerializer Dictionarystring, string dic = new Dictionarystring, string(); dic.Add("id", "1"); dic.Add("name", "jition"); var serializer = new JavaScriptSerializer(); //将object对象转换为字符 var json = serializ

一:使用JavaScriptSerializer

Dictionary<string, string> dic = new Dictionary<string, string>();

dic.Add("id", "1");

dic.Add("name", "jition");

var serializer = new JavaScriptSerializer();

//将object对象转换为字符

var json = serializer.Serialize(dic);

//将json字符转换为object对象

var obj = serializer.Deserialize<Dictionary<string, string>>(json);

二:使用封装方法(DataContractJsonSerializer)

/// <summary>

/// 将C#数据实体转化为JSON数据

/// </summary>

/// <param name="obj">要转化的数据实体</param>

/// <returns>JSON格式字符串</returns>

public static string JsonSerialize<T>(T obj)

{

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

    MemoryStream stream = new MemoryStream();

    serializer.WriteObject(stream, obj);

    stream.Position = 0;

    StreamReader sr = new StreamReader(stream);

    string resultStr = sr.ReadToEnd();

    sr.Close();

    stream.Close();

    return resultStr;

}

/// <summary>

/// 将JSON数据转化为C#数据实体

/// </summary>

/// <param name="json">符合JSON格式的字符串</param>

/// <returns>T类型的对象</returns>

public static T JsonDeserialize<T>(string json)

{

   //json 必须为 {name:"value",name:"value"} 的格式(要符合JSON格式要求)

   DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

   MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json.ToCharArray()));

   T obj = (T)serializer.ReadObject(ms);

   ms.Close();

  return obj;

}

上一篇:C#/VB.NET: 为Excel表格添加超链接
下一篇:没有了
网友评论