分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

Json互相序列化对象

发布时间:2023-09-06 02:16责任编辑:胡小海关键词:暂无标签
using System.ServiceModel;using System.ServiceModel.Web;using System.Runtime.Serialization.Json;using System.IO;namespace Common{ ???public class JsonUtility ???{ ???????public static string getJsonByObject(Object obj) ???????{ ???????????//实例化DataContractJsonSerializer对象,需要待序列化的对象类型 ???????????DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); ???????????//实例化一个内存流,用于存放序列化后的数据 ???????????MemoryStream stream = new MemoryStream(); ???????????//使用WriteObject序列化对象 ???????????serializer.WriteObject(stream, obj); ???????????//写入内存流中 ???????????byte[] dataBytes = new byte[stream.Length]; ???????????stream.Position = 0; ???????????stream.Read(dataBytes, 0, (int)stream.Length); ???????????//通过UTF8格式转换为字符串 ???????????return Encoding.UTF8.GetString(dataBytes); ???????} ???????public static Object getObjectByJson(string jsonString, Object obj) ???????{ ???????????//实例化DataContractJsonSerializer对象,需要待序列化的对象类型 ???????????DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); ???????????//把Json传入内存流中保存 ???????????MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); ???????????// 使用ReadObject方法反序列化成对象 ???????????return serializer.ReadObject(stream); ???????} ???}

  

Json互相序列化对象

原文地址:https://www.cnblogs.com/shiningleo007/p/9718038.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved