非常简单的事情,我出于某种原因无法想出这一点。我有一个看起来像这样的模拟JSON文件:
{
"AccountId":"XXXXXXXXX",
"UAN":"PE3458234758345",
"BillingName":"John Smith",
"BillingAddress": {
"Address1":"701 First Ave.",
"Address2":"test",
"City":"Philadelphia",
"State":"PA",
"Zip:":"19147"
},
"ServiceStartDate":"5/1/2012",
"PromoCode":"0056",
"PartnerCode":"AAL",
"MemberNumber":"0000001",
"Invoices":[
{
"Amount":"113.78",
"Date":"6/1/2012",
"Usage":"3143"
},
{
"Amount":"123.56",
"Date":"7/1/2012",
"Usage":"4561"
},
{
"Amount":"105.23",
"Date":"8/1/2012",
"Usage":"5454"
}
],
"Expected":[
{
"AwardCreation":"true",
"AwardAmount":"500",
"AwardUnits":"usd",
"AwardDate":"today()"
}
]
}
我需要从中创建一个动态对象,因为每次运行测试模型时都会有所不同。我已经尝试了自定义反序列化程序in this solutio以及.NET 4.0 System.Web.Helpers,在这两种情况下我最终得到:
Invalid JSON primitive: \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0...
目前我的工作测试是:
var json = new StringBuilder();
using (var fs = File.Open(@"c:\users\bryan\Desktop\test2.json", FileMode.Open))
{
var byteArray = new byte[1024];
var tempString = new UTF8Encoding(true);
while (fs.Read(byteArray, 0, byteArray.Length) > 0)
{
json.Append(tempString.GetString(byteArray));
}
}
var dynamicObject = Json.Decode(json.ToString());
Assert.IsNotNull(dynamicObject);
我不知道,我想这是格式?我已经从json文件中删除了所有内容(意思是一条巨行),我得到同样的东西。奇怪的是,当我使用Newtonsoft.Json时,我没有得到错误,但动态对象只是AccountId字符串而没有别的。
答案 0 :(得分:2)
您读取UTF-8文件的代码错误,因为它:
考虑使用StreamReader或其他一些内置方法从文件中读取字符串。有关起点,请参阅How to:Read Text from a File和File.ReadAllText。
var dynamicObject = Json.Decode(
File.ReadAllText(@"c:\users\bryan\Desktop\test2.json"));