解决如下json格式的字符串不能使用DataContractJsonSerializer序列化和反序列化 分类: JSON 2015-01-28 14:26 72人阅读 评论(0) 收藏

时间:2023-11-20 23:59:44

可以解决如下json格式的字符串不能使用DataContractJsonSerializer反序列化

{

    "ss": "sss",

    "ss1": "sss",

    "ss2": "sss",

    "ss3": "sss"

}

这样的json反序列化为Dictionary<string, string>对象

需要导入System.Web.Extensions.dll下的System.Web.Script.Serialization命名空间

using System;
using System.Web.Script.Serialization; namespace Imooly.Service.Umeng.MessagePush
{
/// <summary>
/// Json操作帮助类
/// </summary>
/// <remarks>create by chenjinjian.com on 2015-01-26</remarks>
/// <summary>
public static class JsonHelper
{
/// <summary>
/// 对象转换成json
/// </summary>
/// <param name="jsonObject">需要格式化的对象</param>
/// <returns>Json字符串</returns>
/// <remarks>create by chenjinjian.com on 2015-01-26</remarks>
public static string Serialize(object jsonObject)
{
string jsonString = string.Empty;
if (jsonObject != null)
{
var serializer = new JavaScriptSerializer();
jsonString = serializer.Serialize(jsonObject);
}
return jsonString;
} /// <summary>
/// json字符串转换成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString">要转换成对象的json字符串</param>
/// <returns>返回T对象</returns>
/// <remarks>create by chenjinjian.com on 2015-01-26</remarks>
public static T Deserialize<T>(string jsonString)
{
T obj = default(T);
if (!string.IsNullOrEmpty(jsonString))
{
var serializer = new JavaScriptSerializer();
obj = serializer.Deserialize<T>(jsonString);
}
return obj;
}
}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。