TransWikia.com

Change File with extension txt to json in C#

Stack Overflow Asked by azeter09 on December 8, 2020

I have problem with serialized a File this one below to json format.
I would like to make a json file from the file .txt I have attached at the bottom with a helpful serialization. And I need sugestions what exacly I should do to change this file to json format but reading data from a file not included them in code.

.txt –> .json

namespace zadanko
{
  class Program
{
 static void Main(string[] args)
 {

    Console.WriteLine("nEnter path name of file: ");
    var fileName = Console.ReadLine();

    if (!File.Exists(fileName))
    {
        Console.WriteLine("File dosen't exist");
        return;
    }


    FileStream filestream = new FileStream(fileName + "_formatted.json", FileMode.Create);
    var streamwriter = new StreamWriter(filestream);


    streamwriter.AutoFlush = true;
    Console.SetOut(streamwriter);
    Console.SetError(streamwriter);

    StreamReader sr = new StreamReader(fileName);
    string jsonString = sr.ReadToEnd();

    String serialized = JsonConvert.SerializeObject(sr );

    //write all books automatic
    Console.WriteLine(serialized);
    }
  }
 }

 public class Book
{
  public string category { get; set; }
  public string author { get; set; }
  public string title { get; set; }
  public double price { get; set; }
  public string isbn { get; set; }
 }

public class Bicycle
 {
    public string color { get; set; }
    public double price { get; set; }
 }

  public class Store
{
     public List<Book> book { get; set; }
    public Bicycle bicycle { get; set; }
 }

   public class Root
  {
  public Store store { get; set; }
  }

Text:

```text
BOOKS:
 --------------------------------------------------------------------------------- 
 | category  | author           | title                  | price | isbn          |
 --------------------------------------------------------------------------------- 
 | reference | Nigel Rees       | Sayings of the Century | 8,95  |               |
 --------------------------------------------------------------------------------- 
 | fiction   | Evelyn Waugh     | Sword of Honour        | 12,99 |               |
 --------------------------------------------------------------------------------- 
 | fiction   | J. R. R. Tolkien | The Lord of the Rings  | 22,99 | 0-395-19395-8 |
 --------------------------------------------------------------------------------- 
 | fiction   | Evelyn Waugh     | Sword of Honour        | 12,99 |               |
 --------------------------------------------------------------------------------- 

 Count: 4

BICYCLE:
 ----------------- 
 | color | price |
 ----------------- 
 | red   | 19,95 |
 ----------------- 

 Count: 1

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP