我将尝试描述我的处境:
I'll try to describe my situation:
我有Windows Store App(C#),该应用程序从远程数据库( DataBase1 )接收数据,并将其存储在隔离存储( DataBase2 )的本地数据库中.我有一个单独的类,用于所有操作,例如ex的数据:
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; } }该课程可容纳50多个字段.我使用 Newtonsoft.Json :
This class can take 50+ fields. I use Newtonsoft.Json:
var class = JsonConvert.DeserializeObjectAsync<Class1>(json);一切正常,但是在 DataBase1 中,所有字段都具有默认值= null ,当我收到null时,我会遇到异常.
All works great, but in DataBase1 all fields have default value = null, and when I receive null I have exception.
我有2个解决方法:
我的问题是:哪种方法正确?也许您还有另一个想法,如何使用 Newtonsoft.Json 将"null"存储为"0".>尝试解释您的答案.
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.
注意:
还有第三种方法.您可以为此编写一个转换器类
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(); } }更多推荐
替换为"null"到"0"在json中仅用于int还是使用Nullable< int> ;?
发布评论