2

我正在使用 Javascript 序列化程序来解析 JSON 文件。当文件采用有效的 json 格式但失败时,它运行良好,例如最后一个字段中有一个额外的逗号。我怎么能绕过它,我只是从这个文件中检索replicatedid:

{
    "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);
}
4

1 回答 1

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];
于 2012-06-27T19:26:16.593 回答