C#对象与JSON字符串互相转换的几种方式

如题所述

首先你要按JSON的结构定义一个类,类中的变量要用属性的形式
也就是public String XX{get;set;}这样
然后可以参考我下面的代码,是在.NET 4.6下面写的,好像3.5和4.0要用另一个类

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));
}
}
}
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答