Skip to main content
 首页 » 编程设计

c#之反序列化嵌套的 json 字符串导致空值

2024年02月06日25myhome

我有一个 json 字符串,我想将其反序列化以访问特定成员。

string sResponse = "{\"BALANCERESPONSE\":{\"@xmlns\":\"\",\"RESPONSECODE\":\"0\",\"RESPONSEMESSAGE\":\"Success\"}}"; 
Response conObj = new Response(); 
conObj = JsonConvert.DeserializeObject<Response>(sResponse); 
 
public class BALANCERESPONSE 
{ 
    public string RESPONSECODE { get; set; } 
    public string RESPONSEMESSAGE { get; set; } 
} 
 
public class Response 
{ 
    public BALANCERESPONSE resp_onse { get; set; } 
}         

我在 resp_onse 属性中得到一个 null 值。我在这里做错了什么?

请您参考如下方法:

您的输入字符串没有提到名称,而是提到了类型。因此,该属性未被识别并将保持 null。

新:

string sResponse = "{\"resp_onse\":{\"@xmlns\":\"\",\"RESPONSECODE\":\"0\",\"RESPONSEMESSAGE\":\"Success\"}}"; 
                       ^^^^^^^^^ 

旧的:

string sResponse = "{\"BALANCERESPONSE\":{\"@xmlns\":\"\",\"RESPONSECODE\":\"0\",\"RESPONSEMESSAGE\":\"Success\"}}"; 
                       ^^^^^^^^^^^^^^^