[英]Deserialization of inteface types not supported using System.Text.JSON
[英]System.Text.Json JsonSerializer: Serialization and deserialization of 'System.Type' instances are not supported
我想達到什么目標?
我想讓用戶控制在我的數據庫中轉換一些記錄,所以使用可以遵循這個場景:
1- 用戶可以選擇我的類庫的模型。
2- 選擇一個類后,用戶將從這個類中選擇一個屬性(歸檔)。
3- 用戶將獲得所選屬性的值列表。
4- 最后一步現在不在這里,用戶可以編輯一個證書值。
這是我的一段代碼:
MyPage.razor.cs:
[Inject] private IGenericHttpClient<Type> HttpClient { get; set; } private Type SelectedType { get; set; } // First select a class [Class library] from HTML Select private void OnTypeChnage(ChangeEventArgs args) { string FullName = "My.Models." + args.Value.ToString(); // Create type of selected class SelectedType = Assemble.GetType(FullName, false); } //Call api to get all fields of this class private async Task OnPropertChange(ChangeEventArgs args) { var list = await HttpClient.GetJsonAsync($"/api/{SelectedType.Name}/all"); }
通用HttpClient.cs
public async ValueTask<List<T>> GetJsonAsync(string url) { using HttpResponseMessage response = await _client.GetAsync(url); ValidateResponse(response); var conetnt = await response.Content.ReadAsStringAsync(); //I got the error down return JsonSerializer.Deserialize<List<T>>(conetnt, new JsonSerializerOptions() { PropertyNameCaseInsensitive=true}); }
由於安全原因,System.Text.Json 不支持 Type 類。 您將完整的程序集名稱作為字符串發送,然后再次嘗試在客戶端構造類型。
public async ValueTask<List<T>> GetJsonAsync(string url)
這甚至不會編譯,因為沒有指定方法簽名的通用信息。
而且,您的問題將來自 http 響應的內容,否則, Deserialize
步驟應該可以正常工作。
我復制了您的代碼並制作了一個小塊來證明它。
// Define somewhere
public class GenericHttpClient
{
public List<T> GetJsonAsync<T>()
{
var content = "[{\"TestProp\": \"This is some test\"}]";
return JsonSerializer.Deserialize<List<T>>(content, new JsonSerializerOptions() { PropertyNameCaseInsensitive=true});
}
}
public class Test
{
public string TestProp { get; set; }
}
// Test it
var test = new GenericHttpClient();
var result = test.GetJsonAsync<Test>();
就像@Mayur Ekbote 提到的那樣,“出於安全原因,System.Text.Json 不支持 Type 類。” 我會添加一個解決方案,但我認為這個解決方案效率不高。
將Type
更改為Dynamic
:
[Inject] private IGenericHttpClient<dynamic> HttpClient { get; set; }
使用JsonElement
以字符串形式獲取值:
private async Task OnPropertChange(ChangeEventArgs args) { var langCode = CultureInfo.CurrentCulture.Name; PropertyValueList.Clear(); var list = await HttpClient.GetJsonAsync($"/api/{SelectedType.Name}/all"); List<object> listValue = new List<object>(); SelectedProperty = args.Value.ToString(); string fieldName = char.ToLower(SelectedProperty[0]) + SelectedProperty.Substring(1); foreach (var item in list) { //Convert object to JsonElement var val = ((JsonElement)item).GetProperty(fieldName).GetString(); PropertyValueList.Add(val); } }
為什么效率不高?
因為我得到了一個String
值列表而不是所選類的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.