Replace “null” to “0” in json only for int or use Nullable<int>?

久未见 提交于 2021-01-28 15:30:11

问题


I'll try to describe my situation:

I have Windows Store App (C#), which receive data from remote data base (DataBase1), and store it in local database in isolated storage (DataBase2). I have single class for all manipulation with data for ex:

[Table("Table")]
[DataContract]
public class Class1
{
    [PrimaryKey]
    [Column("id")]
    [DataMember(Name = "id")]
    public int Id { get; set; } 
}

This class can take 50+ fields.
I use Newtonsoft.Json:

 var class = JsonConvert.DeserializeObjectAsync<Class1>(json);

All works great, but in DataBase1 all fields have default value = null, and when I receive null I have exception.

I have 2 ideas how to solve it:

  1. make int Id -> int? Id, and in setter change "null" to "0" (and always work with nulleable type), but I'm not sure about performance.
  2. make another nullable field (int? IdCanBeNull), where store value from DataBase1, then in IdCanBeNulls setter set nested value to Id and always work with int Id (not nullable type) (save it in DataBase2 and other). Better performance, but need to create 2xNumberOfFields

My questions is:
Which is right way?
May be you have another idea, how to store "null" to "0" with using Newtonsoft.Json.
Try to explain your answer.

Note:

  1. Yes, when I receive json I can remove all "null" to "0" - but it's isn't good solution.
  2. I can't change default value of DataBase1.

回答1:


There is a third way. You can write a converter class for this

var list = JsonConvert.DeserializeObject<List<Class1>>(
                            "[{Id:5},{Id:0},{Id:null},{}]",
                             new MyConverter());


public class Class1
{
    public int Id { get; set; }
}

public class MyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(int);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.Value == null) return 0;
        return Convert.ToInt32(reader.Value);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}



回答2:


You can try using JsonConverter settings to ignore null characters:

    Person person = new Person
{
    Name = "Nigal Newborn",
    Age = 1
};

string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);

Console.WriteLine(jsonIncludeNullValues);
// {
//   "Name": "Nigal Newborn",
//   "Age": 1,
//   "Partner": null,
//   "Salary": null
// }

string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
});

Console.WriteLine(jsonIgnoreNullValues);
// {
//   "Name": "Nigal Newborn",
//   "Age": 1
// }

more info on: https://www.newtonsoft.com/json/help/html/NullValueHandlingIgnore.htm



来源:https://stackoverflow.com/questions/16835188/replace-null-to-0-in-json-only-for-int-or-use-nullableint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!