使用EmbeddedResourceReader读取json文件 [英] Using EmbeddedResourceReader to read json file
问题描述
我的项目中有一个要测试反序列化正确的json文件。我想使用嵌入式资源来执行此操作。但是,我无法找到正确的方式来获取json文件(目前与我的测试文件位于同一文件夹中)。到目前为止,我已经尝试了以下操作:
I have a json file in my project that I want to test deserializes correctly. I want to use embedded resources to do this. However I can't work out the correct way to get the json file (which is in the same folder as my test file for now). So far I have tried the following:
[Test]
public void JsonDeserializesTest()
{
var reader = new EmbeddedResourceReader(typeof(RatingComponentTests).Assembly, "Components\\UserFeedback");
var json = reader.ReadToEnd("Rating.json");
var jsonData = JsonConvert.DeserializeObject<RatingData>(json);
Assert.IsNotNull(jsonData.results);
}
此方法不适用于 ReadToEnd,这不是有效的方法。我已经尝试过 ReadAsStream,但这会引发错误,我无法将流转换为字符串。
This isn't working with 'ReadToEnd' not being a valid method. I have tried 'ReadAsStream' but this throws the error that I cannot convert a stream to a string.
有人可以指出正确的方向吗?谢谢
Can anyone please point me in the right direction? Thanks
推荐答案
请确保将构建操作
设置为 Rating.json
文件作为嵌入式资源
。使用 GetManifestResourceStream
和 StreamReader
的一种解决方案可以是:
Please make sure to set Build Action
of Rating.json
file as Embedded Resource
. One solution using GetManifestResourceStream
and StreamReader
could be as:
[Test]
public void JsonDeserializesTest()
{
//WindowsTestApp is namespace of project
using (Stream stream = Assembly.GetExecutingAssembly().
GetManifestResourceStream("WindowsTestApp.Rating.json"))
using (StreamReader reader = new StreamReader(stream))
{
var jsonFileContent = reader.ReadToEnd();
var jsonData = JsonConvert.DeserializeObject<IList<RatingData>>(jsonFileContent);
Assert.IsNotNull(jsonData);
}
}
//Test class of json data
public class RatingData
{
public int ID { get; set; }
public int Number { get; set; }
}
JSON文件的示例内容。
The sample contents of JSON file.
//Content of "Rating.json" file
[
{
"ID": 1,
"Number": 1001
},
{
"ID": 2,
"Number": 1002
},
{
"ID": 3,
"Number": 1003
},
{
"ID": 4,
"Number": 1004
}
]
这篇关于使用EmbeddedResourceReader读取json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!