我目前正在尝试读取位于Project文件夹中DataModels文件夹中的Json文件(名为initial_data.json)。我遇到的问题是它不会读取文件。我已经尝试了以下代码将文件读取到json字符串(稍后我将用它来反序列化,所以我试图将它显示在resultTextBlock中)并且没有任何结果。 这是我的Json文件格式
{
"brands": [
{
"id": "AUD",
"name": "AUDI",
"sort": "99",
"active": true
},
{
"id": "BEN",
"name": "MERCEDES-BENZ",
"sort": "6",
"active": true
},
{
"id": "BMW",
"name": "BMW",
"sort": "7",
"active": true
},
{
"id": "CHE",
"name": "CHEVROLET",
"sort": "8",
"active": true
}
],
"models": [
{
"id": "100",
"name": "CIVIC",
"brandID": "HON",
"size": null,
"year": "-",
"active": true
},
{
"id": "101",
"name": "CRV",
"brandID": "HON",
"size": null,
"year": "-",
"active": true
},
{
"id": "102",
"name": "CRVEXI",
"brandID": "HON",
"size": null,
"year": "-",
"active": true
},
{
"id": "103",
"name": "GDYSSEY",
"brandID": "HON",
"size": null,
"year": "-",
"active": true
}
]
}
这是我的json Class
public class Brand
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("sort")]
public string sort { get; set; }
[JsonProperty("active")]
public bool active { get; set; }
[JsonProperty("path")]
public string path { get; set; }
}
public class Model
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("brandID")]
public string brandID { get; set; }
[JsonProperty("size")]
public object size { get; set; }
[JsonProperty("year")]
public string year { get; set; }
[JsonProperty("active")]
public bool active { get; set; }
}
以下是我编写阅读功能的方法
private async Task readJsonAsync()
{
// Notice that the write **IS** identical ... except for the serializer.
string content = String.Empty;
var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(JSONFILENAME);
using (StreamReader reader = new StreamReader(myStream))
{
content = await reader.ReadToEndAsync();
}
resultTextBlock.Text = content;
}
任何帮助将不胜感激
答案 0 :(得分:0)
认为您为文件名指定的路径可能存在一些问题。
请将您的文件放在资源文件夹中,并按照以下代码
var fileStream = File.OpenRead("Assets/" + "sampleJson.txt");//You can specify your file name here.
using (StreamReader reader = new StreamReader(fileStream))
{
var content = await reader.ReadToEndAsync();
}