Json数据转成 C# asp.net数据(对象)和逆转换

时间:2021-08-04 10:59:54

1.需要引用的命名空间

using System.Web.Script.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

2.Json数据转成 C# asp.net数据(对象)方法如下

MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<yourType>));////youType是与Json格式对应的C#类
StreamWriter wr = new StreamWriter(stream);
wr.Write(tabJson); //tabJson是你需要转化的Json字符串
wr.Flush();
stream.Position = 0;
Object obj = ser.ReadObject(stream);
List<yourType> list = (List<yourType>)obj; //list即为转化成的c#对象集合,通过索引如list[0],list[1]等访问。
int length = list.Count();//length为list对象集合的对象个数

3.如上方法的json字符串必须为如下格式,就是数组

[
{
"ID": "1",
"fieldName": "MANDT",
"fieldDisc": "客户端",
"fieldType": "String",
"mainGuid": "7cc70e2e-dea7-495b-85ac-639a202b4c86",
"subGuid": "b95a98f5-7b7d-4060-96c7-3088cbab1fe4"
},
{
"ID": "2",
"fieldName": "VKORG",
"fieldDisc": "销售主体",
"fieldType": "String",
"mainGuid": "7cc70e2e-dea7-495b-85ac-639a202b4c86",
"subGuid": "1ae34ef2-ac94-47c6-8589-59b41d5054ef"
}
]

而对应的yourType的类型如下:

public class yourType
{
public int ID { get; set; }
public string fieldName { get; set; }
public string fieldDisc { get; set; }
public string fieldType { get; set; }
public string mainGuid { get; set; }
public string subGuid { get; set; }
}

4. C# asp.net数据(对象)转成Json数据

JavaScriptSerializer serializer = new JavaScriptSerializer();  
var jsonData = serializer.Serialize(list);  


相关文章