C#对象转Json和Json转对象
//--需要引⽤:System.Web.Extensions.dll
//---对象结构---
public class object_data
{
public int code { get; set; }
public string msg { get; set; }
public List<string> list_str { get; set; }
public List<items> list_items { get; set; }
}
public class items
object to
{
public int value1 { get; set; }
public int value2 { get; set; }
}
/// <summary>
/// 将Json字符串转换为对象-
/// </summary>
/// <param name="JsonData"></param>
/// <returns></returns>
public object_data JsonToObject(string JsonStr)
{
/
/实例化⼀个能够序列化数据的类
JavaScriptSerializer js = new JavaScriptSerializer();
//将json数据转化为对象类型并赋值给list
object_data dataObject = js.Deserialize<object_data>(JsonStr);
//返回对象
return dataObject;
}
/// <summary>
/// 将对象转换为-Json字符串
/// </summary>
/// <param name="data"></param>
/
// <returns></returns>
public string ObjectToJson(object_data data)
{
StringBuilder sb = new StringBuilder();
JavaScriptSerializer json = new JavaScriptSerializer();
json.Serialize(data, sb);
return sb.ToString();
}
//--测试例⼦---
string str_json = "{\"code\":1,\"msg\":\"测试\",\"list_str\":[11,12,13,14,15],\"list_items\":[{\"value1\":100,\"value2\":101},{\"value1\":102,\"value2\":103}]}";        //转换为对象-
object_data test_obj = JsonToObject(str_json);
//换为-Json字符串
string test_str = ObjectToJson(test_obj);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。