我在将下面的文件序列化为json格式时遇到问题。我想从底部附加的文件 .txt 制作一个 json 文件,并带有有用的序列化。而且我需要建议我应该做些什么来将此文件更改为 json 格式,但从文件中读取数据不包含在代码中。
.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