[TOC]
# JSON
JSON类封装应该是项目中最常用的类之一
## Stringify
将对象转为一个JSON字符串
```
string jsonStr = JSON.Stringify(jsonObj);
```
函数定义如下
```
//2022.3.20新增JSON自定义options
public string Stringify(object obj, JsonSerializerOptions jsonSerializerOptions, string dateFormat = "yyyy/MM/dd HH:mm:ss")
public string Stringify(object obj, bool camelCase = false, string dateFormat = "yyyy/MM/dd HH:mm:ss", bool nullIgnore = false)
// camelCase 全部小写
// dateFormat 时间转化格式
// nullIgnore 值为null时忽略
```
## To
将字符串转换为对象
```
//转换成模型实例
Model.Company model = JSON.To<Model.Company>(jsonString);
//转换成字典
Dictionary<string, object> dict = JSON.To<Dictionary<string, object>>(jsonString);
```
## ToOrNew
如果你希望在To返回是null时进行自动实例化处理可以使用该函数
如下:
```
var model = JSON.To<Model.Company>(jsonString)
if (model == null)
{
model = new Model.Company();
}
```
使用ToOrNew的情况
```
var model = JSON.ToOrNew<Model.Company>(jsonString)
```
## JSON.Document
JSON.Document 是为了方便对JSON对象进行操作
将任意对象转换成JSON.Document
```
//json可以为字符串 \ 字典 \ 模型
var document = new JSON.Docuemtn(json);
```
### 获取值
```
//获取字符串
document.GetString("key");
//获取布尔值
document.GetBoolean("key");
//获取整数int
document.GetInt("key");
//获取长整形long
document.GetInt64("key");
//获取double
document.GetDouble("key");
//获取decimal
document.GetDecimal("key");
//获取datetime
document.GetDateTime("key");
```
### 特殊取值
```
//获取子Document
document.GetDocument("key");
//获取字典
document.GetDictionary("key");
document.ToDictionary("key");
//当前对象
document.ToDictionary();
//获取列表
document.GetList<T>("key");
//2022.03.20新增
//获取Document列表
document.GetList("key");
//2022.04.25新增
//获取Model
document.GetModel<Model.Company>("key");
```
如果key不存在则会抛出LCException提示键不存在,但有时候我们又不希望阻断程序,这个使用我们就可以加上 OrDefault 后缀
### OrDefault 后缀
```
document.GetStringOrDefault("key", "");
```
或者可以在程序中判断是否存在
```
if(document.ContainsKey("key"))
{
// CODE...
}
```
### 补充说明
- 关于时间格式, 为了兼容移动端的前端格式需求,所以内置统一格式为 "yyyy/MM/dd HH:mm:ss"
- 关于字符串的转化, Number类型也针对性做了处理
- 2022-06-24 如果整数或字符串类型的整数 转 浮点不会报错