//************************************************************************
// https://github.com/yuzhengyang
// author: yuzhengyang
// date: 2017.3.29 - 2018.10.19
// desc: Json转换工具类(需要Newtonsoft.Json支持)
// Copyright (c) yuzhengyang. All rights reserved.
//************************************************************************
using Azylee.Core.IOUtils.TxtUtils;
using Newtonsoft.Json;
using System;
using System.Text;
namespace Azylee.Jsons
{
///
/// Json 工具
///
public class Json
{
///
/// 对象 转 字符串
///
///
///
public static string Object2String(object obj)
{
return JsonConvert.SerializeObject(obj);
}
///
/// 字符串 转 对象
///
///
///
public static object String2Object(string s)
{
string json = s;
if (!string.IsNullOrWhiteSpace(json))
{
try { return JsonConvert.DeserializeObject(json); } catch (Exception e) { }
}
return null;
}
///
/// 字符串 转 模型
///
///
///
///
public static T String2Object(string s)
{
string json = s;
if (!string.IsNullOrWhiteSpace(json))
{
try { return JsonConvert.DeserializeObject(json); } catch (Exception e) { }
}
return default(T);
}
///
/// 读取文件文本 转 模型
///
///
///
///
public static T File2Object(string file)
{
string json = TxtTool.Read(file);
if (!string.IsNullOrWhiteSpace(json))
{
try { return JsonConvert.DeserializeObject(json); } catch (Exception e) { }
}
return default(T);
}
///
/// 对象 转 字节(JSON中转)
///
///
///
public static byte[] Object2Byte(object obj)
{
try
{
string s = JsonConvert.SerializeObject(obj);
byte[] b = Encoding.UTF8.GetBytes(s);
return b;
}
catch { return null; }
}
///
/// 字节 转 模型(JSON中转)
///
///
///
public static T Byte2Object(byte[] b)
{
try
{
string s = Encoding.UTF8.GetString(b);
return JsonConvert.DeserializeObject(s);
}
catch { return default(T); }
}
}
}