Home > database >  C# Newtonsoft Json Writing in as [Json] instead of just JSON
C# Newtonsoft Json Writing in as [Json] instead of just JSON

Time:09-30

I am using C# to parse from ninjatrader given data every minute, which is then read in and inserted into a json file, currently it looks like the following: enter image description here

Which is okay but I need it to be in the following format:

[
{Data1},
{Data2},
...
{DataN}
]

or just

{Data1},
{Data2},
...
{DataN}

without the []

The following is my current code:

public class DataFormat
{
    public DateTime Date { get; set; }
    public double PriceChange { get; set; }
    public double RSI { get; set; }
    public double Momentum { get; set; }
    public double MACD { get; set; }
}


sw = File.AppendText(path);  // Open the path for writing

List<DataFormat> _data = new List<DataFormat>();
_data.Add(new DataFormat()
{
    Date = Time[0],
    PriceChange = Close[0] - Open[0],
    RSI = RSI(20, 3)[0],
    Momentum = Momentum(20)[0],
    MACD = MACD(12, 26, 9)[0]
});
string json = JsonConvert.SerializeObject(_data);
sw.WriteLine(json);
sw.Close(); // Close the file to allow future calls to access the file again.

What is the best way to get it to read in as a JSON {}?

CodePudding user response:

In your logic you serialize one object at a time and then adding it to a file. So just remove List<DataFormat> and instead just do _data = new DataFormat() Then the only thing you would need to do is to add "," - you need to add it manually, basically sw.WriteLine($"{json},")

  •  Tags:  
  • c#
  • Related