Blazor WASM(.NET 8)中如何将缓存的JSON响应反序列化为Kontent AI强类型对象
Blazor WASM(.NET 8)中如何将缓存的JSON响应反序列化为Kontent AI强类型对象
嘿,我之前也踩过这个坑!用Kontent AI自动生成的强类型模型,把数据存成JSON缓存后反序列化老是失败,折腾了好一阵子才找到靠谱的解决办法,给你分享下:
首先得搞懂为啥会失败——Kontent生成的强类型类里包含了很多它自己特有的元素类型(比如富文本、资产、多选选项这些),默认的JSON序列化/反序列化工具根本不知道怎么处理这些特殊类型,所以直接存完再读肯定报错。
我最推荐的解决方法就是复用Kontent SDK自带的序列化配置,因为官方SDK已经帮我们把所有特殊类型的转换器、命名规则都配置好了,不用自己瞎折腾:
用System.Text.Json的情况(.NET 8 Blazor WASM默认)
Kontent的IDeliveryClient实例里已经自带了预配置好的JsonSerializerOptions,我们直接拿来用就行:
- 首先在你的组件/服务里注入
IDeliveryClient - 缓存和读取的时候,都用这个预配置的Options来序列化和反序列化
代码示例大概是这样的:
// 先注入DeliveryClient和本地存储(Blazor WASM常用IAsyncLocalStorage) private readonly IDeliveryClient _deliveryClient; private readonly IAsyncLocalStorage _localStorage; public YourComponent(IDeliveryClient deliveryClient, IAsyncLocalStorage localStorage) { _deliveryClient = deliveryClient; _localStorage = localStorage; } // 读取缓存或从Kontent拉取数据的方法 private async Task<RichTextModulesType> GetRichTextModuleData() { // 先从缓存里读JSON var cachedJson = await _localStorage.GetItemAsStringAsync("rich-text-module-cache"); if (string.IsNullOrEmpty(cachedJson)) { // 缓存没数据,就从Kontent拉取 var kontentResponse = await _deliveryClient.GetItemAsync<RichTextModulesType>("你的内容项代号"); var modelToCache = kontentResponse.Item; // 用Kontent的配置序列化后存缓存 var jsonToCache = JsonSerializer.Serialize(modelToCache, _deliveryClient.JsonSerializerOptions); await _localStorage.SetItemAsStringAsync("rich-text-module-cache", jsonToCache); return modelToCache; } else { // 用Kontent的配置反序列化缓存的JSON return JsonSerializer.Deserialize<RichTextModulesType>(cachedJson, _deliveryClient.JsonSerializerOptions); } }
用Newtonsoft.Json的情况(如果你项目里用了这个)
要是你项目里习惯用Newtonsoft而不是System.Text.Json,逻辑也差不多——直接用IDeliveryClient里预配置的JsonSerializerSettings就行:
// 同样先注入IDeliveryClient和缓存服务 private async Task<RichTextModulesType> GetRichTextModuleData() { var cachedJson = await _localStorage.GetItemAsStringAsync("rich-text-module-cache"); if (string.IsNullOrEmpty(cachedJson)) { var kontentResponse = await _deliveryClient.GetItemAsync<RichTextModulesType>("你的内容项代号"); var modelToCache = kontentResponse.Item; // 用Kontent的Newtonsoft配置序列化 var jsonToCache = JsonConvert.SerializeObject(modelToCache, _deliveryClient.JsonSerializerSettings); await _localStorage.SetItemAsStringAsync("rich-text-module-cache", jsonToCache); return modelToCache; } else { // 用Kontent的配置反序列化 return JsonConvert.DeserializeObject<RichTextModulesType>(cachedJson, _deliveryClient.JsonSerializerSettings); } }
几个要注意的小坑
- 缓存的时候,尽量只存Kontent返回的Item对象(也就是
response.Item),别存整个DeliveryResponse,因为里面有一堆元数据,反序列化更容易出问题 - 别随便修改Kontent自动生成的partial类,比如自己加
[JsonPropertyName]这类特性,很容易和SDK的配置冲突 - 要是你非得自己手动配置序列化选项,那得把Kontent所有用到的元素转换器都加上(比如
RichTextElementConverter、AssetElementConverter这些),但真的没必要,用SDK现成的配置香多了
备注:内容来源于stack exchange,提问作者Đức Thành Nguyễn
相关产品推荐
相关产品推荐

