我正在使用 Javascript 序列化器来解析 JSON 文件。当文件采用有效的 json 格式时,它运行良好,但会失败,例如最后一个字段中有一个额外的逗号。我怎样才能绕过这个问题,我只是从此文件中检索replicateid:
{
"Orders":
[
{
"Rack": "0014",
"SampleType": "Calibrator",
"Replicate": 3,
"Track": 1,
"Lane": 2,
"ReagentMasterLot": "06100AA02",
"ReagentSerialNumber": "60002",
"Comment": "HTLV Cal T1L2",
}
]
}
public static KeyValuePair<bool, int> CyclesCompleted(string fileName)
{
int cyclesCompleted = 0;
JavaScriptSerializer ser = jss();
bool isValid = true;
try
{
CategoryTypeColl ctl = ser.Deserialize<CategoryTypeColl>(LoadTextFromFile(fileName));
if (ctl != null)
{
List<CategoryType> collection = (from item in ctl.orders
select item).ToList();
foreach (var replicates in collection)
{
cyclesCompleted = cyclesCompleted + replicates.Replicate;
}
}
}
catch
{
isValid = false;
}
return new KeyValuePair<bool, int>(isValid, cyclesCompleted);
}
最佳答案
您应该使用JSON.NET 。它是一个开源库,用于将 .net 对象序列化和反序列化为 json 字符串,反之亦然。它几乎解决了 .net json 序列化不能解决的问题。
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
关于c# - Javascript 序列化器额外的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11233475/