简体   繁体   English

System.Text.Json JsonSerializer:不支持“System.Type”实例的序列化和反序列化

[英]System.Text.Json JsonSerializer: Serialization and deserialization of 'System.Type' instances are not supported


I got an error related with security when I tried to deserialize by using `System.Text.Json JsonSerializer`. 当我尝试使用“System.Text.Json JsonSerializer”进行反序列化时,出现了与安全相关的错误。
  • What do I want to achieve?我想达到什么目标?
    I want to give the user controle to transalte some records in my database, so use can follow this scenario:我想让用户控制在我的数据库中转换一些记录,所以使用可以遵循这个场景:

    1- User can choose model of my class library. 1- 用户可以选择我的类库的模型。
    2- After selecting a class, user will select a property(filed) from this class. 2- 选择一个类后,用户将从这个类中选择一个属性(归档)。
    3- User will get list of values of the selected property up. 3- 用户将获得所选属性的值列表。
    4- Last step is not here right now, user can edit a certian value. 4- 最后一步现在不在这里,用户可以编辑一个证书值。

This my piece of code:这是我的一段代码:

  • MyPage.razor.cs: 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"); }
  • GenericHttpClient.cs通用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 does not support Type class due to security reasons.由于安全原因,System.Text.Json 不支持 Type 类。 You send the full assembly name as a string and again try to construct the Type at the client end.您将完整的程序集名称作为字符串发送,然后再次尝试在客户端构造类型。

public async ValueTask<List<T>> GetJsonAsync(string url) this wont even compile, due to not specify generic information on method signature. public async ValueTask<List<T>> GetJsonAsync(string url)这甚至不会编译,因为没有指定方法签名的通用信息。

And also, your problem would come from the content of http response, otherwise, the Deserialize step should work fine.而且,您的问题将来自 http 响应的内容,否则, Deserialize步骤应该可以正常工作。

I copied your code and make a small block that prove it.我复制了您的代码并制作了一个小块来证明它。

// 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>();

Like what @Mayur Ekbote mentioned up, "System.Text.Json does not support Type class due to security reasons."就像@Mayur Ekbote 提到的那样,“出于安全原因,System.Text.Json 不支持 Type 类。” I will add a solution but I don't think this solution is very efficient.我会添加一个解决方案,但我认为这个解决方案效率不高。

  • Change Type to Dynamic :Type更改为Dynamic

     [Inject] private IGenericHttpClient<dynamic> HttpClient { get; set; }
  • Use JsonElement to get the value as a string:使用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); } }
  • Why is it not efficient?为什么效率不高?
    Because I got a list of value String instead of list of selected class.因为我得到了一个String值列表而不是所选类的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 System.Text.JSON 不支持反序列化接口类型 - Deserialization of inteface types not supported using System.Text.JSON Select 类型用于 System.Text.Json 中的反序列化 - Select type to use for deserialization in System.Text.Json 使用 System.Text.Json 自定义反序列化 - Custom deserialization with System.Text.Json System.Text.Json object 数组反序列化 - System.Text.Json object array deserialization System.Text.Json 自定义序列化/反序列化 - System.Text.Json Custom Seriallization / Deserialization System.Text.Json 中是否可以进行多态反序列化? - Is polymorphic deserialization possible in System.Text.Json? 使用 C# System.Text.Json 对带有混合大小写的 json 文本进行序列化/反序列化 - Serialization/deserialization of json text with mix casing for property names using C# System.Text.Json 具有资源 model PUT 的 WebAPI 项目中 System.Type 的序列化/反序列化 - Serialization/Deserialization of System.Type in WebAPI Project with resource model PUT JsonSerializer.反序列化<t> (); 在 System.Text.Json 中没有正确反序列化</t> - JsonSerializer.Deserialize<T>(); in System.Text.Json not deserialize correctly System.Text.Json JsonSerializer.反序列化<tvalue> (...) 无法反序列化 object[] 类型</tvalue> - System.Text.Json JsonSerializer.Deserialize<TValue>(...) cannot deserialize object[] type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM