Hej,
Mam problem z otworzeniem pliku który był zmieniony z jsona na .txt. Chciałabym zmienić dane w pliku który jest sformatowany(.txt) i z powrotem przekonwertować do jsona. Jednak nie do konca wiem jak się za to zabrać. Mogłabym prosić chociaż o małą podpowiedz?
using ConsoleTables;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace zadanko
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\nEnter file name with extension ");
var fileName = Console.ReadLine();
if (!File.Exists(fileName))
{
Console.WriteLine("File dosent exist");
return;
}
FileStream filestream = new FileStream(fileName + "_formatted.txt", 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();
Root deserialized = JsonConvert.DeserializeObject<Root>(jsonString);
Console.WriteLine("BOOKS:");
//write all books automatic
ConsoleTable.From<Book>(deserialized.store.book).Write();
//write all books manual
// var booksTable = new ConsoleTable("title", "author", "category", "isbn", "price");
// foreach (var book in deserialized.store.book)
// {
// booksTable.AddRow(book.title, book.author, book.category, book.isbn, book.price);
// }
// booksTable.Write();
Console.WriteLine();
//show bicycle
Console.WriteLine("BICYCLE:");
var bicycleTable = new ConsoleTable("color", "price");
bicycleTable.AddRow(deserialized.store.bicycle.color, deserialized.store.bicycle.price);
bicycleTable.Write();
}
}
}
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; }
}
**Plik json: **
{
"store": {
"book": [{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
},
],
"bicycle": { "color": "red", "price": 19.95 }
}
}
Po kompilacji:
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 |
Count: 3
BICYCLE:
| color | price |
| red | 19,95 |
Count: 1