0
点赞
收藏
分享

微信扫一扫

C# DataContractJsonSerializer 处理Json

霸姨 2023-09-18 阅读 35


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;

namespace Common
{
    public class JsonHelper
    {
        public static string JsonToString<T>(T value)
        {
            using (var vStream = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(vStream, value);
                byte[] jsondata = new byte[vStream.Length];
                vStream.Position = 0;
                if (vStream.Read(jsondata, 0, jsondata.Length) != jsondata.Length)
                    throw new Exception("读取出错");
                return Encoding.UTF8.GetString(jsondata);
            }
        }

        public static T StringToJson<T>(string text)
        {
            byte[] jsondata = Encoding.UTF8.GetBytes(text);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            using (var vStream = new MemoryStream(jsondata))
            {
                return (T)serializer.ReadObject(vStream);
            }
        }
    }
}



举报

相关推荐

0 条评论