using Nancy.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MaterialTraceability.Common
{
///
/// Json格式转换
///
public class JsonChange
{
///
/// Model 实体转json
///
/// 可以是单个实体,也可是实体集(即:ToList())
///
public static string ModeToJson(object Model)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
try
{
string str = serializer.Serialize(Model);
return str;
}catch(Exception ex)
{
LogHelper.Info("Model转Json异常:" + ex.Message);
return "";
}
}
///
/// json实体转Model
///
///
///
///
public static T JsonToMode(string jsonStr)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
try
{
var info = serializer.Deserialize(jsonStr);
return info;
}
catch (Exception ex)
{
LogHelper.Info("Json转Model异常:" + ex.Message);
return default(T);
}
}
///
/// object转dictionary
///
///
///
public static Dictionary objectToDictionary(string jsonData)
{
Dictionary result = new Dictionary();
var inf = JsonConvert.DeserializeObject>(jsonData);
foreach (KeyValuePair 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 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 ite in info)
{
result.Add(item.Key + ite.Key, ite.Value);
}
continue;
}
}
result.Add(item.Key, item.Value);
}
return result;
}
}
}