问题
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:
- 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. - make another nullable field (
int? IdCanBeNull
), where store value from DataBase1, then inIdCanBeNull
s setter set nested value toId
and always work withint Id
(not nullable type) (save it inDataBase2
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:
- Yes, when I receive json I can remove all "null" to "0" - but it's isn't good solution.
- 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