I'm working with an API that returns a string which looks like this:
{
"id": "835166796775451164",
"username": "˞˞˞˞˞˞˞˞˞˞˞˞˞˞˞˞˞˞˞˞",
"avatar": "x",
"discriminator": "1391",
"public_flags": 0,
"flags": 0,
"purchased_flags": 2,
"locale": "en-US",
"nsfw_allowed": true,
"mfa_enabled": false,
"premium_type": 2,
"email": "x",
"verified": false,
"phone": null
}
and an object to deserialize this JSON:
public class User
{
[JsonProperty(PropertyName ="id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "username")]
public string Username { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "discriminator")]
public string Discriminator { get; set; }
[JsonProperty(PropertyName ="phone")]
public string Phone { get; set; }
[JsonProperty(PropertyName ="verfied")]
public string Verified { get; set; }
}
However when I try to Deserialize the received JSON string to that object and call it, it returns a "null" value. This is my code for deserialization:
if (responseHtml.IsSuccessStatusCode)
{
var json = await responseHtml.Content.ReadAsStringAsync();
User user= JsonConvert.DeserializeObject<User>(json);
}
I also tried making a wrapper from this Deserialization of JSON.Net returns 'null' :
public class UserWrapper
{
public User User { get; set; }
}
but it also returned a null value
static async Task Main(string[] args)
{
await utilities.FetchAccountInformation();
Models.User user= new Models.User();
Console.WriteLine(user.Username);
}
I fixed it and just in case somebody faced the same problem I'd like to post a solution on how I managed to solve it. Basically what I did was adding this class that appends additional settings onto a serializer:
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
and then adding it as a parameter to the DeserializeObject method such as:
User user= JsonConvert.DeserializeObject<User>(json, Converter.Settings);
I hope it helps somebody.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.