我正在使用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; }
}
答案 0 :(得分:2)
使用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);
和deserilaize as
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; }
}