我已经和JSON.net合作了一段时间.我已经编写了自定义转换器和自定义合同解析器(通常来自修改SO和Newtonsoft网站上的示例),它们工作正常.
除了例子之外,我面临的挑战是,我什么时候应该使用其中一个(或两个)进行处理.根据我自己的经验,我基本上已经确定合同解决方案更简单了,所以如果我可以用他们做我需要的东西,我会这样做; 否则,我使用自定义JsonConverters.但是,我进一步知道两者有时一起使用,因此概念变得更加不透明.
问题:
Json.Net通常将a序列Dictionary<k,v>化为集合;
"MyDict": {
"Apples": {
"Taste": 1341181398,
"Title": "Granny Smith",
},
"Oranges": {
"Taste": 9999999999,
"Title": "Coxes Pippin",
},
}
Run Code Online (Sandbox Code Playgroud)
哪个好.从环顾四周看似乎是大多数人想要的东西.但是,在这种特殊情况下,我想在我的Dictionary<k,v>和Array格式之间进行序列化;
"MyDict": [
"k": "Apples",
"v": {
"Taste": 1341181398,
"Title": "Granny Smith",
}
},
"k:": "Oranges",
"v:": {
"Taste": 9999999999,
"Title": "Coxes Pippin",
}
},
]
Run Code Online (Sandbox Code Playgroud)
使用我现有的字段类型有一种简单的方法吗?有没有我可以注释的属性?
我正在使用json.net来实现winform应用程序的memento模式.我正在使用memento在失败的数据库事务上回滚对象.我得到的问题是,当反序列化纪念品时,调用getter而不是setter.让我来证明:
class MyClass
{
public int ID { get; set; }
public string field1 { get; set; }
public string field2 { get; set; }
private List<SomeObject> _someObjects;
public List<SomeObject> SomeObjects
{
get
{
if(_someObjects == null)
{
_someObjects = LoadSomeObjectsFromDB();
}
return _someObjects;
}
set
{
_someObjects = value;
}
}
private List<AnotherObject> _anotherObjects;
public List<AnotherObject> AnotherObjects
{
get
{
if(_anotherObjects == null)
{
_anotherObjects= LoadAnotherObjectsFromDB();
}
return _anotherObjects ;
}
set
{
_anotherObjects = value;
} …Run Code Online (Sandbox Code Playgroud) 这是代码:
public class ParameterDictionary : Dictionary<HydroObjectIdentifier, string>
{
public void WriteToJson(string jsonFilePath)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(this, formatting: Newtonsoft.Json.Formatting.Indented);
System.IO.File.WriteAllText(jsonFilePath, json);
}
}
public struct HydroObjectIdentifier
{
public string Name { get; set; }
public string TypeName { get; set; }
public HydroObjectIdentifier(string name, string typeName)
{
this.Name = name;
this.TypeName = typeName;
}
}
Run Code Online (Sandbox Code Playgroud)
...这就是Json的结果。请注意,它显示的是类名RSEngine.HydroObjectIdentifier而不是其参数,这在我的代码中不是预期的。
{
"RSEngine.HydroObjectIdentifier": [
{
"myString"
},
...
Run Code Online (Sandbox Code Playgroud)
如注释中所述,预期的行为是将Name和TypeName写入json而不是类的名称。