C#从外部作用域访问数据表

时间:2017-09-21 04:51:46

标签: c# json while-loop datatable scope

我有带有2个对象的JSON文件...对于此示例“Country”和“Data”。我正在尝试将“Data”对象反序列化为数据表“sortedFileData”,但无法从while循环内部访问数据表。我已经找到了如何创建一个新类(C#: access variable in the inner scope from the outer scope)如何解决,但我不会在这里做。

        using (FileStream fs = new FileStream(selectedProject, FileMode.Open, FileAccess.Read))
        using (StreamReader sr = new StreamReader(fs))
        using (JsonTextReader reader = new JsonTextReader(sr))
        {
            DataTable sortedFileData = new DataTable();
            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.StartObject)
                {
                    // Load each object from the stream and do something with it
                    JObject obj = JObject.Load(reader);
                    System.Windows.MessageBox.Show((string)obj["Country"]);
                    DataTable sortedFileData = JsonConvert.DeserializeObject<DataTable>((string)obj["Data"]);
                }
            }
        }

        string sorted = "Name ASC, Age ASC, Date ASC";
        DataView dtView = new DataView(sortedFileData) {Sort = sorted};

示例JSON:

 {
  "Country": "England",
  "Data": [
    {
      "Name": "Bill",
      "Age": "70",
      "Date": "2015-05-27"
    },
    {
      "Name": "Sara",
      "Age": "36",
      "Date": "2015-01-21"
    },
    {
      "Name": "Bob",
      "Age": "7",
      "Date": "2011-05-24"
    }
  ]
}

1 个答案:

答案 0 :(得分:2)

你可以在循环之外声明它并将它分配到同一个地方。

    DataTable sortedFileData;

    using (FileStream fs = new FileStream(selectedProject, FileMode.Open, FileAccess.Read))
    using (StreamReader sr = new StreamReader(fs))
    using (JsonTextReader reader = new JsonTextReader(sr))
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.StartObject)
            {
                // Load each object from the stream and do something with it
                JObject obj = JObject.Load(reader);
                System.Windows.MessageBox.Show((string)obj["Country"]);
                sortedFileData = JsonConvert.DeserializeObject<DataTable>((string)obj["DataTable1"]);
            }
        }
    }

    string sorted = "Name ASC, Age ASC, Date ASC";
    if (sortedFileData != null) 
    {
        DataView dtView = new DataView(sortedFileData) {Sort = sorted};
    }

然后你可以做一个快速的空检查,以确保一切都按预期进行。