Home > Enterprise >  Deserialize text file into JSON object with key value
Deserialize text file into JSON object with key value

Time:09-30

I have txt file(not json file) which is like the format below. I need to deserialize it into key and value string if possible but I just need it to read the txt file and extract the values such as MulTwoNumbers, Multiplying two numbers, etc, then assign it into string variables.

I tried to use StreamReader and read it line by line and try to match the Regex pattern but it is troublesome for me and did not work as intended. Here is the Regex pattern that I used, I only tried to get _name value because I didn't know how to get all those other values:

Regex regex = new Regex(@"(?<=_name\x22:\x22)\w ");
{"_name":"MulTwoNumbers","_description":"Multiplying two numbers","_api_endpoint":"http://localhost:64780/api/calculator/MulTwoNumbers","number_operand":"2","_operand_type":"integer"}
{"_name":"ADDThreeNumbers","_description":"Adding three numbers","_api_endpoint":"http://localhost:64780/api/calculator/ADDThreeNumbers","number_operand":"3","_operand_type":"integer"}

CodePudding user response:

You could do something like this (exact syntax not checked):

dynamic json = System.Text.Json.JsonSerializer.Deserialize<ExpandoObject>(SINGLE_LINE_OF_TEXT_FILE);
var keyValue =  new KeyValuePair<string,string>(json._name, json._number_operand); 

CodePudding user response:

you can create a custom class and add your data to a List

    List<Data> dataList = new();
    using (StreamReader reader = new StreamReader(fileName))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            Data data = System.Text.Json.JsonSerializer.Deserialize<Data>(line);
            dataList.Add(data);
        }
    }

or you can try this

     string text = File.ReadAllText(fileName);
    string[] lines = text.Split(Environment.NewLine,  StringSplitOptions.RemoveEmptyEntries);
    foreach (string line in lines)
    {
        Data data = System.Text.Json.JsonSerializer.Deserialize<Data>(line);
        dataList.Add(data);
    }

class

public partial class Data
{
    [JsonPropertyName("_name")]
    public string Name { get; set; }

    [JsonPropertyName("_description")]
    public string Description { get; set; }

    [JsonPropertyName("_api_endpoint")]
    public Uri ApiEndpoint { get; set; }


    [JsonPropertyName("number_operand")]
    public string NumberOperand { get; set; }

    [JsonPropertyName("_operand_type")]
    public string OperandType { get; set; }
}
  • Related