如何从resx文件中打开json文件?

huangapple go评论105阅读模式
英文:

How do I open json file from resx file?

问题

我有一个resources.resx文件和一个resources文件夹。我尝试从中获取一个json文件。

项目结构:如何从resx文件中打开json文件?

我拥有的代码

  1. string resxFile = @".\resources.resx";
  2. using (ResXResourceSet resxSet = new ResXResourceSet(resxFile)) {
  3. using (JsonDocument document = JsonDocument.Parse((FileStream)resxSet.GetObject("allCivs"))) {
  4. ...
  5. }
  6. }

我收到了这个错误:如何从resx文件中打开json文件?

据我了解,我没有正确指定“resx”文件的路径,因为程序试图在“bin”文件夹中找到此文件。

我应该如何正确指定路径?我读取json文件的后续操作是否正确?

编辑:

allCivs.json中的数据(只有两个元素,总共有43个类似的元素):

  1. "Austria": {
  2. "Лидер": [
  3. {
  4. "image": "civStuffIcons/Австрия_Лидер1.png",
  5. "Мария Терезия": {
  6. "Персоналия": "Дипломатическая уния:Позволяет тратить золото на то, чтобы присоединять или делать сателлитами города-государства, которые оставались вашими союзниками 5 и более ходов."
  7. }
  8. }
  9. ],
  10. "Уникальный юнит": [
  11. {
  12. "image": "civStuffIcons/Австрия_Уникальный юнит1.png",
  13. "Гусар": {
  14. "Эпоха": "Новейшее время",
  15. "Замещает": "Кавалерист",
  16. "Сила": "34"
  17. }
  18. }
  19. ],
  20. "Уникальное здание": [
  21. {
  22. "image": "civStuffIcons/Австрия_Уникальное здание1.png",
  23. "Кофейня": {
  24. "Замещает": "Мельница",
  25. "Эффект": "+5% ед. продукции +2 ед. продукции Увеличивает на 25% ОВЛ скорость возникновения великих людей в городе.Может быть построена в любом городе."
  26. }
  27. }
  28. ],
  29. "Флаг": "civsFlags/austria.png"
  30. },
  31. {
  32. "America":{
  33. ...
  34. }
  35. }

Resources中的数据:如何从resx文件中打开json文件?

我需要循环遍历此文件,并且,例如,获取所有国家名称(在此示例中为“Austria”、“America”)。

英文:

I have resources.resx file and I have resources folder. I'm trying to get one json file from it.

project structure: 如何从resx文件中打开json文件?

code I have

  1. string resxFile = @".\resources.resx";
  2. using (ResXResourceSet resxSet = new ResXResourceSet(resxFile)) {
  3. using (JsonDocument document = JsonDocument.Parse((FileStream)resxSet.GetObject("allCivs"))) {
  4. ...
  5. }
  6. }

I get this error:如何从resx文件中打开json文件?

As far as I understand, I am not correctly specifying the path to the "resx" file, because the program tries to find this file in the "bin" folder.

How can I correctly specify the path to it? Are my further actions for reading the json file correct?

EDIT:

data inside allCivs.json(just two elements,there are 43 like those):

  1. "Austria": {
  2. "Лидер": [
  3. {
  4. "image": "civStuffIcons/Австрия_Лидер1.png",
  5. "Мария Терезия": {
  6. "Персоналия": "Дипломатическая уния:Позволяет тратить золото на то, чтобы присоединять или делать сателлитами города-государства, которые оставались вашими союзниками 5 и более ходов."
  7. }
  8. }
  9. ],
  10. "Уникальный юнит": [
  11. {
  12. "image": "civStuffIcons/Австрия_Уникальный юнит1.png",
  13. "Гусар": {
  14. "Эпоха": "Новейшее время",
  15. "Замещает": "Кавалерист",
  16. "Сила": "34"
  17. }
  18. }
  19. ],
  20. "Уникальное здание": [
  21. {
  22. "image": "civStuffIcons/Австрия_Уникальное здание1.png",
  23. "Кофейня": {
  24. "Замещает": "Мельница",
  25. "Эффект": "+5% ед. продукции +2 ед. продукции Увеличивает на 25% ОВЛ скорость возникновения великих людей в городе.Может быть построена в любом городе."
  26. }
  27. }
  28. ],
  29. "Флаг": "civsFlags/austria.png"
  30. },
  31. {
  32. "America":{
  33. ...
  34. }
  35. }

data inside Resources: 如何从resx文件中打开json文件?

I need to loop through this file and, for example, get all country names(in this example it's "Austria","America")

答案1

得分: 1

最终代码

  1. string resxFile = @".\resources.resx";
  2. List<string> _listCountry = new List<string>();
  3. using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
  4. {
  5. byte[] allCivs = (byte[])resxSet.GetObject("allCivs");
  6. var texts = System.Text.Encoding.UTF8.GetString(allCivs, 0, allCivs.Length);
  7. var jsonObject = JObject.Parse(texts);
  8. foreach (var x in jsonObject)
  9. {
  10. _listCountry.Add(x.Key);
  11. }
  12. }

附加信息

  1. 解决第一个问题的方法是,你必须更改资源文件 resources.resx 的 "Copy to output directory" 属性。

    1. 右键点击 resources.resx -> 属性。
    2. 将 'Copy to output directory' 更改为 "Copy Always" 或 "Copy if Newer"。
  2. 读取一个键的值,你可以使用以下代码:

  1. var Value = resxSet.GetString("allCivs");
  1. 读取所有键值对,你可以使用以下代码:
  1. foreach (DictionaryEntry entry in resxSet)
  2. {
  3. string resourceKey = entry.Key.ToString();
  4. object resource = entry.Value;
  5. }
  1. 你可以使用以下代码从 JSON 文件中获取所有国家的列表:
  1. using Newtonsoft.Json.Linq;
  2. string text = File.ReadAllText(@"Test.json");
  3. var jsonObject = JObject.Parse(text);
  4. List<string> _list = new List<string>();
  5. foreach (var x in jsonObject)
  6. {
  7. _list.Add(x.Key);
  8. }
英文:

Fist, get file "allCivs" ,then you must parse json "allCivs" and Find Countries

Final Code

  1. string resxFile = @&quot;.\resources.resx&quot;;
  2. List&lt;string&gt; _listCountry = new List&lt;string&gt;();
  3. using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
  4. {
  5. byte[] allCivs =(byte[]) resxSet.GetObject(&quot;allCivs&quot;);
  6. var texts = System.Text.Encoding.UTF8.GetString(allCivs, 0, allCivs.Length);
  7. var jsonObject = JObject.Parse(texts);
  8. foreach (var x in jsonObject)
  9. {
  10. _listCountry.Add(x.Key);
  11. }
  12. }

Additional information

1.Way Solve Fist Problem ,you must change "Copy to output directory" properties on file resources.resx

> 1.Right click resources.resx -> properties.
>
> 2.Change 'Copy to output directory' to "Copy Always" or "Copy if Newer "

2.Read a key, you can use below code

  1. var Value = resxSet.GetString(&quot;allCivs&quot;);
  2. //using (JsonDocument document = JsonDocument.Parse((string)resxSet.GetObject(&quot;Test&quot;)))
  3. //{
  4. // var d = &quot;&quot;;
  5. //}

3.Read all of keys, you can use below code

  1. foreach (DictionaryEntry entry in resxSet)
  2. {
  3. string resourceKey = entry.Key.ToString();
  4. object resource = entry.Value;
  5. }

4.You can get List Country in json file with use below code

  1. using Newtonsoft.Json.Linq;
  2. string text = File.ReadAllText(@&quot;Test.json&quot;);
  3. var jsonObject = JObject.Parse(text);
  4. List&lt;string&gt; _list = new List&lt;string&gt;();
  5. foreach (var x in jsonObject)
  6. {
  7. _list.Add(x.Key);
  8. }

huangapple
  • 本文由 发表于 2023年6月16日 03:05:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定