The json file follows:
[{"Id":0,"Nome":"","Endereco":""}]
Follow the class:
public class JsonResult
{
public int Id { get; set; }
public string Nome { get; set; }
public string Endereco { get; set; }
}
Follow the code below:
string jsonToOutput = string.Empty;
using (StreamReader r = new StreamReader($@"{pathname}\file.json"))
{
string json = r.ReadToEnd();
var array = JArray.Parse(json);
List<JsonResult> items = JsonConvert.DeserializeObject<List<JsonResult>>(json);
var last = items[items.Count - 1].Id + 1;
var itemToAdd = new JObject
{
["Id"] = last,
["Nome"] = textBox_nome.Text,
["Endereco"] = textBox_endereco.Text
};
array.Add(itemToAdd);
jsonToOutput = JsonConvert.SerializeObject(array, Formatting.None);
}
using (StreamWriter file = File.CreateText($@"{pathname}\file.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, jsonToOutput);
}
Result I want:
[{"Id":0,"Nome":"","Endereco":""},{"Id":1,"Nome":"","Endereco":""}]
Final result:
"[{\"Id\":0,\"Nome\":\"\",\"Endereco\":\"\"},{\"Id\":1,\"Nome\":\"\",\"Endereco\":\"\"}]"
Second attempt:
string jsonToOutput = string.Empty;
using (StreamReader r = new StreamReader($@"{pathname}\file.json"))
{
string json = r.ReadToEnd();
List<JsonResult> items = JsonConvert.DeserializeObject<List<JsonResult>>(json);
int last = items[items.Count - 1].Id + 1;
List<JsonResult> _data = new List<JsonResult>
{
new JsonResult()
{
Id = last,
Nome = "",
Endereco = ""
}
};
items.AddRange(_data);
jsonToOutput = JsonConvert.SerializeObject(items);
}
using (StreamWriter file = File.CreateText($@"{pathname}\file.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, jsonToOutput);
}
Any solution?