Newtonsoft 六个超简单又实用的特性，值得一试 【下篇】

06/24 09:10

二：特性分析

1. 像弱类型语言一样解析 json

{
"DisplayName": "新一代算法模型",
"CustomerType": 1,
"Report": {
"TotalCustomerCount": 1000,
},
"CustomerIDHash": [1,2,3,4,5]
}

static void Main(string[] args)
{
var json = @"{
'DisplayName': '新一代算法模型',
'CustomerType': 1,
'Report': {
'TotalCustomerCount': 1000,
},
'CustomerIDHash': [1,2,3,4,5]
}";

var dict = JsonConvert.DeserializeObject<Dictionary<object, object>>(json);

var report = dict["Report"] as JObject;
var totalCustomerCount = report["TotalCustomerCount"];

Console.WriteLine(\$"totalCustomerCount={totalCustomerCount}");

var arr = dict["CustomerIDHash"] as JArray;
var list = arr.Select(m => m.Value<int>()).ToList();

Console.WriteLine(\$"list={string.Join(",", list)}");
}

2. 如何让json中的枚举保持更易读的字符串型

static void Main(string[] args)
{

var json = JsonConvert.SerializeObject(model);

Console.WriteLine(json);
}

{
}

var json = JsonConvert.SerializeObject(model, new StringEnumConverter());

static void Main(string[] args)
{
var model = new ThreadModel()
{
};

var json = JsonConvert.SerializeObject(model);

Console.WriteLine(json);
}

{

[JsonConverter(typeof(StringEnumConverter))]
public TaskStatus TaskStatusEnum { get; set; }
}

3. 格式化 json 中的时间类型

static void Main(string[] args)
{
var json = JsonConvert.SerializeObject(new Order()
{
OrderTitle = "女装大佬",
Created = DateTime.Now
}, new JsonSerializerSettings
{
DateFormatString = "yyyy年/MM月/dd日",
});

Console.WriteLine(json);
}
public class Order
{
public string OrderTitle { get; set; }
public DateTime Created { get; set; }
}

4. 对一些常用设置进行全局化

JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
return settings;
};

var order = new Order() { OrderTitle = "女装大佬", Created = DateTime.Now };

var json1 = JsonConvert.SerializeObject(order);
var json2 = JsonConvert.SerializeObject(order);

Console.WriteLine(json1);
Console.WriteLine(json2);

5. 如何保证 json 到 model 的严谨性 及提取 json 未知字段

• 未知字段报错

static void Main(string[] args)
{
var json = "{'OrderTitle':'女装大佬', 'Created':'2020/6/23','Memo':'订单备注'}";

var order = JsonConvert.DeserializeObject<Order>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error
});

Console.WriteLine(order);
}

public class Order
{
public string OrderTitle { get; set; }
public DateTime Created { get; set; }
public override string ToString()
{
return \$"OrderTitle={OrderTitle}, Created={Created}";
}
}

• 提取未知字段

static void Main(string[] args)
{
var json = "{'OrderTitle':'女装大佬', 'Created':'2020/6/23','Memo':'订单备注'}";

var order = JsonConvert.DeserializeObject<Order>(json);

Console.WriteLine(order);
}

public class Order
{
public string OrderTitle { get; set; }

public DateTime Created { get; set; }

[JsonExtensionData]
private IDictionary<string, JToken> _additionalData;

public Order()
{
_additionalData = new Dictionary<string, JToken>();
}

[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
var dict = _additionalData;
}

public override string ToString()
{
return \$"OrderTitle={OrderTitle}, Created={Created}";
}
}

6. 开启 JsonConvert 详细日志功能

static void Main(string[] args)
{
var json = "{'OrderTitle':'女装大佬', 'Created':'2020/6/23','Memo':'订单备注'}";

MemoryTraceWriter traceWriter = new MemoryTraceWriter();

var account = JsonConvert.DeserializeObject<Order>(json, new JsonSerializerSettings
{
TraceWriter = traceWriter
});

Console.WriteLine(traceWriter.ToString());
}

public class Order
{
public string OrderTitle { get; set; }

public DateTime Created { get; set; }

public override string ToString()
{
return \$"OrderTitle={OrderTitle}, Created={Created}";
}
}

1
0 收藏

06/24 09:15

1 评论
0 收藏
1