|
|
using Newtonsoft.Json;
|
|
|
using Newtonsoft.Json.Linq;
|
|
|
using System;
|
|
|
using System.Collections.Generic;
|
|
|
using System.Linq;
|
|
|
using System.Text;
|
|
|
using System.Threading.Tasks;
|
|
|
using System.Web.Script.Serialization;
|
|
|
using System.Xml.Linq;
|
|
|
|
|
|
namespace FileDataUpload.Common
|
|
|
{
|
|
|
public class JsonChange
|
|
|
{
|
|
|
|
|
|
private static readonly Lazy<JsonChange> lazy = new Lazy<JsonChange>(() => new JsonChange());
|
|
|
|
|
|
public static JsonChange Instance
|
|
|
{
|
|
|
get
|
|
|
{
|
|
|
return lazy.Value;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private JsonChange() { }
|
|
|
|
|
|
/// <summary>
|
|
|
/// Model 实体转json
|
|
|
/// </summary>
|
|
|
/// <param name="Model">可以是单个实体,也可是实体集(即:ToList())</param>
|
|
|
/// <returns></returns>
|
|
|
public string ModeToJson(object Model)
|
|
|
{
|
|
|
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
|
|
try
|
|
|
{
|
|
|
string str = serializer.Serialize(Model);
|
|
|
return str;
|
|
|
}
|
|
|
catch (Exception)
|
|
|
{
|
|
|
return "";
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// json实体转Model
|
|
|
/// </summary>
|
|
|
/// <typeparam name="T"></typeparam>
|
|
|
/// <param name="jsonStr"></param>
|
|
|
/// <returns></returns>
|
|
|
public T JsonToMode<T>(string jsonStr)
|
|
|
{
|
|
|
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
|
|
try
|
|
|
{
|
|
|
var info = serializer.Deserialize<T>(jsonStr);
|
|
|
return info;
|
|
|
}
|
|
|
catch (Exception)
|
|
|
{
|
|
|
return default(T);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// object转dictionary
|
|
|
/// </summary>
|
|
|
/// <param name="jsonData"></param>
|
|
|
/// <returns></returns>
|
|
|
public Dictionary<string, object> objectToDictionary(string jsonData)
|
|
|
{
|
|
|
Dictionary<string, object> result = new Dictionary<string, object>();
|
|
|
|
|
|
var inf = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);
|
|
|
|
|
|
foreach (KeyValuePair<string, object> item in inf)
|
|
|
{
|
|
|
if (item.Value != null)
|
|
|
{
|
|
|
var type = item.Value.GetType();
|
|
|
if (type == typeof(JObject))
|
|
|
{
|
|
|
var info = objectToDictionary(JsonConvert.SerializeObject(item.Value));
|
|
|
foreach (KeyValuePair<string, object> ite in info)
|
|
|
{
|
|
|
result.Add(ite.Key, ite.Value);
|
|
|
}
|
|
|
continue;
|
|
|
}
|
|
|
else if (type == typeof(JArray))
|
|
|
{
|
|
|
JArray array = (JArray)item.Value;
|
|
|
var info = objectToDictionary(JsonConvert.SerializeObject(array[0]));
|
|
|
foreach (KeyValuePair<string, object> ite in info)
|
|
|
{
|
|
|
result.Add(item.Key + ite.Key, ite.Value);
|
|
|
}
|
|
|
continue;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
result.Add(item.Key, item.Value);
|
|
|
}
|
|
|
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
} |