贴上一个简单的Json帮助类,代码如下:
public class JsonHelper
{
/// <summary>
/// 实体类转Json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
public T JsonStringToClass<T>(string jsonString)
{
using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonString)))
{ return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms); }
}
/// <summary>
/// Json转实体类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonObject"></param>
/// <returns></returns>
public string ClassToJsonString<T>(T jsonObject)
{
using (var ms = new MemoryStream())
{
new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// Json格式化
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public string JsonFormate(string json)
{
int Level = 0;
var JsonArr = json.ToArray();
string JsonTree = string.Empty;
for(int i = 0; i < json.Length; i++)
{
char c = JsonArr[i];
if (Level > 0 && ‘\n‘ == JsonTree.ToArray()[JsonTree.Length - 1])
{
JsonTree += TreeLevel(Level);
}
switch (c)
{
//case ‘{‘:
// JsonTree +="\r\n"+c ;
// break;
//case ‘}‘:
// JsonTree += "\r\n"+c;
//break;
case ‘[‘:
JsonTree += c + "\r\n";
Level++;
break;
case ‘,‘:
JsonTree += c + "\r\n";
break;
case ‘]‘:
JsonTree += "\r\n";
Level--;
JsonTree += TreeLevel(Level);
JsonTree+=c;
break;
default:
JsonTree += c;
break;
}
}
return JsonTree;
}
string TreeLevel(int level)
{
string leaf = string.Empty;
for (int t = 0; t < level; t++)
{
leaf += "\t";
}
return leaf;
}
/// <summary>
/// Json文件格式化
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public string JsonFileFormatte(string filepath)
{
try
{
if (!File.Exists(filepath))
{
return "传入文件不存在!";
}
string str = File.ReadAllText(filepath);
str = JsonFormate(str);
File.WriteAllText(filepath, str);
return "操作已成功!";
}catch(Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Json转成实体类
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public dynamic ConvertJsonToDynamic(string json)
{
javascriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic dy = jss.Deserialize(json, typeof(object)) as dynamic;
return dy;
}
}
class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type == typeof(object))
{
return new DynamicJsonObject(dictionary);
}
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
}
}
class DynamicJsonObject : DynamicObject
{
private IDictionary<string, object> Dictionary { get; set; }
public DynamicJsonObject(IDictionary<string, object> dictionary)
{
this.Dictionary = dictionary;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this.Dictionary[binder.Name];
if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
else if (result is ArrayList)
{
result = new List<object>((result as ArrayList).ToArray());
}
return this.Dictionary.ContainsKey(binder.Name);
}
}