我正在使用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);
}
答案 0 :(得分:2)
您应该使用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];