主程序代码
controller.modelToFile("passwords/test.json");
controller.deJSONizeModel("passwords/test.json");
控制器的modelToFile:
public void modelToFile(String filename) {
System.IO.File.WriteAllText(filename, JSONizeModel());
}
控制器的JSONizeModel:
public String JSONizeModel() {
Newtonsoft.Json.JsonSerializerSettings jss = new Newtonsoft.Json.JsonSerializerSettings();
jss.Formatting = Newtonsoft.Json.Formatting.Indented;
Newtonsoft.Json.Serialization.DefaultContractResolver dcr = new Newtonsoft.Json.Serialization.DefaultContractResolver();
dcr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;
jss.ContractResolver = dcr;
return Newtonsoft.Json.JsonConvert.SerializeObject(model, jss);
}
控制器的deJSonizeModel:
public void deJSONizeModel(String json) {
model = JsonConvert.DeserializeObject<Model>(json);
}
模型:
class Model : IModel {
private IList<Password> passwords = new List<Password>();
<...>
文件test.json:
{
"passwords": [
{
"description": "example password 1",
"password": "p1"
},
{
"description": "example password 2",
"password": "p2"
},
{
"description": "This is the password",
"password": "the password"
}
]
}
密码类:
public String description { get; set; }
public String password { get; set; }
public Password(String description, String password) {
this.description = description;
this.password = password;
}
请帮助。异常是Newtonsoft.Json.JSONReaderException.
程序日志:
A first chance exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
A first chance exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Additional information: Error parsing boolean value. Path '', line 0, position 0.
解决了!deJSONizeModel
的参数是一个FILE,但需要JSON !