Home > Net >  Converting dictionary from .txt file to C# variable
Converting dictionary from .txt file to C# variable

Time:04-16

I need help with converting a dictionary from some .txt file to a variable in C#. Take a look at this picture below (the .txt file):

The txt file

As you can see, there is a dictionary in which are other two dictionaries. I want to ask if it is possible to convert it to an actual C# dictionary. Now, the .txt file does not correspond to C# obviously, because I just don't know how to do that or if it is even possible.

I have this code below to just open the file and read it line by line:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class MapLoader: MonoBehaviour
{
   void Start()
   {
       string mapID = "SGT589H";

       string path = $"Maps/{mapID}.txt";

       Dictionary<string, string> map = new Dictionary<string, string>();

       using (var file = new StreamReader(path))
       {
           string line = null;

           bool skip = false;

           while ((line = file.ReadLine()) != null)
           { 
               ........
           }
       }
   }
}

Don't mind the Unity Engine, it doesn't matter in my question. So my goal is to take the dictionary from the .txt file and save it in the C# dictionary named "map" so I can work with the dictionary later (it will be generating maps based on the data, I will be saving them as .txt files, not as unity scenes, to save space and then use my MapHandler to load them). As you can see, the <string, string> doesn't correspond too.

My question is, is there any way how to achieve that or could you possibly give me some ideas on how I would be able to change the structure to be able to do that? Thank you.

CodePudding user response:

If you decide to take path of interpreting this json-like format yourself you need to write serializer to convert Python structures into C# which can get quite complicated as you need to think about different types of objects (arrays, booleans, integers and floating points), how you read each line and symbol etc.

Plus, the fact that you're trying to store values of different types (again, arrays, booleans, integers) into String will give you a headache of serialization of those values when you try to access and use them later.

If you can change how and in which format you get the input, I suggest you to stick to pure JSON for this case and interpret it using any third-party library or extension (first Google search gave me official MS docs and Json.NET). Of course, method of storing data will change (that is, probably more than a single Dictionary object) but it definitely will be more organized and easy to use.

  • Related