【问题标题】:Have more then one Json object per file using Json.net使用 Json.net 每个文件有多个 Json 对象
【发布时间】:2013-12-28 19:04:53
【问题描述】:

我正在开发 Windows 应用商店应用程序并遇到了问题, 目前我可以像这样读取 .json 文件:

{
  "Name": "TestItem2",
  "Category": "Undefined",
  "Sum": 10.2,
  "Date": "28/12/2013"
}

使用此代码:

async public static Task addCostsInDB(string name, double sum, string desc) 
    {
        StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        StorageFile file2 = await storageFolder.CreateFileAsync("costs.json", Windows.Storage.CreationCollisionOption.OpenIfExists);

        Costs newCosts = new Costs
           {
               Name = name,
               Sum = sum,
               Category = "Undefined",
               Date = System.DateTime.Now.Day.ToString() + "/" + System.DateTime.Now.Month.ToString() + "/" + System.DateTime.Now.Year.ToString()
           };  

            var obj = newCosts;
            JsonSerializer serializer = new JsonSerializer();
            string json = JsonConvert.SerializeObject(obj, Formatting.Indented);


            //await FileIO.WriteTextAsync(file, json);
            await Windows.Storage.FileIO.WriteTextAsync(file2, json);

            ReadJson.ReadJson.addCostsInDB();

            bool done = await updateVariables();

            while (done == false)
            {

            }

            return;
    }

但是,每个文件我只能读取一个对象。我需要能够像这样读取 json 文件:

[
{
  "Name": "TestItem1",
  "Category": "Undefined",
  "Sum": 10.2,
  "Date": "28/12/2013"
},
{
  "Name": "TestItem2",
  "Category": "Undefined",
  "Sum": 10.2,
  "Date": "28/12/2013"
},
{
  "Name": "TestItem3",
  "Category": "Undefined",
  "Sum": 10.2,
  "Date": "28/12/2013"
},
{
  "Name": "TestItem4",
  "Category": "Undefined",
  "Sum": 10.2,
  "Date": "28/12/2013"
}
]

谢谢:D

编辑: 这是“成本”类:

public class Costs
{
    public string Name { get; set; }
    public string Category { get; set; }
    public double Sum { get; set; }
    public string Date { get; set; }
}

【问题讨论】:

    标签: c# .net json xaml windows-store-apps


    【解决方案1】:

    使用List<Costs>进行序列化/反序列化......

    首先初始化你的对象

    List<Costs> list = new List<Costs>()
    {
        {new Costs{Name="name1",Category="c1",Sum=10,Date = DateTime.Now}},
        {new Costs{Name="name2",Category="c2",Sum=20,Date = DateTime.Now}}
    };
    

    序列化为

    string json = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented);
    

    反序列化为

    var list2 = JsonConvert.DeserializeObject<List<Costs>>(json);
    

    public class Costs
    {
        public string Name { get; set; }
        public string Category { get; set; }
        public double Sum { get; set; }
        public DateTime Date { get; set; }
    }
    

    【讨论】:

    • 谢谢,这真的很有帮助:D
    猜你喜欢
    • 2021-09-19
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    相关资源
    最近更新 更多