c#怎么把对象转换成json字符串
1个回答
2017-07-20 · 知道合伙人软件行家
关注
展开全部
DoNet2.0 需要借助于Newtonsoft.Json.dll
代码
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace OfflineAcceptControl.UCTools
{
public class JsonTools
{
// 从一个对象信息生成Json串
public static string ObjectToJson(object obj)
{
return JavaScriptConvert.SerializeObject(obj);
}
// 从一个Json串生成对象信息
public static object JsonToObject(string jsonString, object obj)
{
return JavaScriptConvert.DeserializeObject(jsonString, obj.GetType());
}
}
}
Donet3.5自带了DLL处理json串
注意引用:System.Runtime.Serialization,System.ServiceModel.Web
代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace CrjIIOfflineAccept.CrjIITools
{
public class JsonTools
{
// 从一个对象信息生成Json串
public static string ObjectToJson(object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, obj);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
return Encoding.UTF8.GetString(dataBytes);
}
// 从一个Json串生成对象信息
public static object JsonToObject(string jsonString, object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
return serializer.ReadObject(mStream);
}
}
}
代码
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace OfflineAcceptControl.UCTools
{
public class JsonTools
{
// 从一个对象信息生成Json串
public static string ObjectToJson(object obj)
{
return JavaScriptConvert.SerializeObject(obj);
}
// 从一个Json串生成对象信息
public static object JsonToObject(string jsonString, object obj)
{
return JavaScriptConvert.DeserializeObject(jsonString, obj.GetType());
}
}
}
Donet3.5自带了DLL处理json串
注意引用:System.Runtime.Serialization,System.ServiceModel.Web
代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace CrjIIOfflineAccept.CrjIITools
{
public class JsonTools
{
// 从一个对象信息生成Json串
public static string ObjectToJson(object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, obj);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
return Encoding.UTF8.GetString(dataBytes);
}
// 从一个Json串生成对象信息
public static object JsonToObject(string jsonString, object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
return serializer.ReadObject(mStream);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询