Home > Blockchain >  How to write a line in a 'array' in a JSON file
How to write a line in a 'array' in a JSON file

Time:11-18

I wrote a code in C# that get the user input and saves it in a JSON file, but like I need a database, that means that I'll need write several lines, but that's the problem, the code do not put it inside the []. Here is the output:

[
    {"modelo":"gtr","ano":2004,"cor":"branco","marca":"nissan","placa":"123abc","completo":"sim","potencia":500},
    {"modelo":"gol","ano":2023,"cor":"preto","marca":"volkswagen","placa":"23b4ab","completo":"sim","potencia":130},
{"modelo":"enzo","ano":2015,"cor":"vermelho","marca":"ferrari","placa":"123456a","completo":"sim","potencia":700}


]

As you can see, the lines inside the [], I put manually, that one below is automatic by the code, I have to put that line inside the [].

{"modelo":"292","ano":11,"cor":"11","marca":"292","placa":"1","completo":"11","potencia":1}

and here is the code:

string jsonString = JsonSerializer.Serialize(estoque);

Console.WriteLine(jsonString);

string filePath = @"C:\Users\willi\Desktop\programas\CarDataBase\data.json";

    List<string> lines = new List<string>();
    lines = File.ReadAllLines(filePath).ToList();
 
    foreach (string line in lines)
    {
        Console.WriteLine(line);
    }
 
    lines.Add(jsonString);
   // lines.Add();
    lines.Add("");
    File.WriteAllLines(filePath, lines);

I have to put the lines(output) inside the [], as I explained above

CodePudding user response:

But what is JsonSerializer created for? You should read your file, deserialize it into a C# List of Estoque objects, add a new item to the list, serialize the C# List, and rewrite your file.

UPDATE: here's an implementation.

string data = File.ReadAllText("YourFilePath"); // using System.IO

var array = await JsonSerializer.DeserializeAsync<Estoque[]>(data); // using System.Text.Json

if (array == null) {
  // Error. Do something
  return;
}

var list = new List<Estoque>(array); // using System.Collections.Generic

list.Add(estoque); // Add your new object

var newArray = list.ToArray();

string json = await JsonSerializer.SerializeAsync<Estoque[]>(newArray);

File.WriteAllText("YourFilePath", json);

CodePudding user response:

I recommend you to use Newtonsoft.Json, code will be much simpler not only here but in the most cases in the future.

    using Newtonsoft.Json;

    string json = File.ReadAllText(filePath);

    var arr = JArray.Parse(json);
    
    var newObj = JObject.FromObject(estoque);

    arr.Add(newObj);

    json = arr.ToString();

    File.WriteAllText(filePath, json);

or more compact

    var arr = JArray.Parse(File.ReadAllText(filePath));
    arr.Add(JObject.FromObject(estoque);
    File.WriteAllText(filePath, arr.ToString());
  • Related