简体   繁体   中英

Newtosoft JSON Deserialize zero string value ( {'name': '0'} ) to null?

I have a problem when deserializing JSON with a string property value of "0". It gets deserialized to null .

{
  "name":"Some name",
  "isConfigProperty":true,
  "displayProperty":false,
  "default":"0"
}

This is my class to deserialize to:

public class PropertyModel
{
   public string Name { get; set; }   
   public bool IsConfigProperty { get; set; }
   public bool DisplayProperty { get; set; }
   public string Default { get; set; }
}

When I change Default value from "0" to "1" or any other number/value it deserializes as it should. But when I change it to "0", I get null again.

Does anyone know about this? Is it possibly a bug in NewtonsoftJson or am I missing something?

Thank you.

You can use JsonConverterAttribute annotation: to define type for a property.

public enum UserStatus
{
    NotConfirmed,
    Active,
    Deleted
}

public class User
{
    public string UserName { get; set; }

    [JsonConverter(typeof(StringEnumConverter))]
    public UserStatus Status { get; set; }
}

Doc

it was solved. Something strange must have happened in Visual Studio debugger or maybe I just don't know that (I'm new in ASP.NET/Core/Microsoft) As it looks when debugging Blazor webassembly sometimes or in cases I don't know some variables are shown with null value when debugging... when in reallity they are not null. I figured it out when I implemented logging to file and "default":"0" was 0 and not null.

Also thank you for all the answers you provided and sorry for causing this issue before I tried with all the solutions.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM