Skip to main content
 首页 » 编程设计

c#之在 C# 中使用 DataContractJsonSerializer 使用 List> 反序列化 JSON 对象

2024年02月13日15jackei

我想反序列化一个包含单个成员的 JSON 对象;字符串数组:

{"errores":[{"errorCode":"campo1","errorMessage":"Errorenelcampo1"},{"errorCode":"campo2","errorMessage":"Errorenelcampo2"},{"errorCode":"campo3","errorMessage":"Errorenelcampo3"},{"errorCode":"campo4","errorMessage":"Errorenelcampo4"}]}" 

这是我要反序列化的类:

[DataContract] 
internal class rptaNo 
{ 
    [DataMember] 
    public List<Errors> errores { get; set; } 
 
    [DataContract] 
    protected internal struct Errors 
    { 
        [DataMember] 
        public string codigo { get; set; } 
        [DataMember] 
        public string descripcion { get; set; } 
    } 
} 

这是我尝试反序列化的方法:

public T Deserialise<T>(string json) 
{ 
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T)); 
    using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json))) 
    { 
        T result = (T)deserializer.ReadObject(stream); 
        return result; 
    } 
} 

但是当我检查时,子列表的所有字段都是空白的,例如

MessageBox.Show(deserializedRpta2.errores[0].descripcion); 

我想一定是我遗漏了什么 = (

请您参考如下方法:

您的模型需要具有与 JSON 对象名称相匹配的属性:

[DataContract] 
protected internal struct Errors 
{ 
    [DataMember] 
    public string errorCode { get; set; } 
    [DataMember] 
    public string errorMessage { get; set; } 
}