如何将C#/.NET 将json字符串格式数据转换成对象?

如题所述

第1个回答  2022-12-11

首先你要按JSON的结构定义一个类,类中的变量要用属性的形式.


也就是public String XX{get;set;}这样.


然后可以参考我下面的代码,是在.NET 4.6下面写的,好像3.5和4.0要用另一个类.


1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24


25


26


27


28


using System;


using System.Collections.Generic;


using System.IO;


using System.Linq;


using System.Runtime.Serialization.Json;


using System.Text;


using System.Web;



namespace XXX


{


public class clsJson


{


public static T Deserialize<T>(String s) where T : class


{


DataContractJsonSerializer dataContractJsonSerializer = new 

DataContractJsonSerializer(typeof(T));


MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(s));


return dataContractJsonSerializer.ReadObject(memoryStream) as T;


}


public static String Serialize<T>(T t) where T : class


{


DataContractJsonSerializer dataContractJsonSerializer = new 

DataContractJsonSerializer(typeof(T));


MemoryStream memoryStream = new MemoryStream();


dataContractJsonSerializer.WriteObject(memoryStream, t);


return Encoding.UTF8.GetString(memoryStream.ToArray(), 0, 

Convert.ToInt32(memoryStream.Length));


}


}


}

相关了解……

你可能感兴趣的内容

大家正在搜

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网