如何解决System.Text.Json.Deserialize数组成C#类
首先,我正在使用Google recaptcha RESTful服务,尝试将JSON对象放入类中。使用WSDL,Visual Studio会为您生成所有这些代码,以便于使用,但是RESTful似乎您必须自己做所有事情,我是否有所遗漏?我正在使用VS2019,可能会想到有某种方法可以导入这些东西以使生活变得轻松。我还没找到任何东西,所以...
Google返回:
{
"success": false,"error-codes": [
"invalid-input-response","invalid-input-secret"
]
}
我想反序列化为这个:
[DataContract]
public class GoogleReCaptchaResponse
{
[DataMember(Name = "success")]
public bool Success { get; set; }
[DataMember(Name = "error-codes")]
public List<string> ErrorCodes { get; set; }
[JsonExtensionData]
public Dictionary<string,object> ExtensionData { get; set; }
}
我在ExtensionData中看到了错误代码,但是ErrorCodes始终为null。我怎么了?
https://dotnetfiddle.net/RtjbwR
解决方法
您应该使用JsonPropertyName
命名空间中的System.Text.Json.Serialization
属性
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class GoogleReCaptchaResponse
{
[JsonPropertyName("success")]
public bool Success { get; set; }
[JsonPropertyName("error-codes")]
public List<string> ErrorCodes { get; set; }
}
public class Program
{
public static void Main()
{
GoogleReCaptchaResponse json = System.Text.Json.JsonSerializer.Deserialize<GoogleReCaptchaResponse>("{ \"success\": false,\"error-codes\": [\"invalid-input-response\",\"invalid-input-secret\"]}");
if (json.ErrorCodes == null)
{
Console.WriteLine("no Error Codes");
}
else
{
Console.WriteLine("Error Codes!");
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。