0
Follows json file:
[{"Id":0,"Nome":"","Endereco":""}]
Follows the class:
public class JsonResult
{
public int Id { get; set; }
public string Nome { get; set; }
public string Endereco { get; set; }
}
Follows code:
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 that 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);
}
Some solution ?
Have you tried printing the value of
jsonToOutput
to see if he’s right? I think the error is there– mutlei
What is the difference between the result obtained and the expected?
– Jéf Bueno
@LINQ In the original file is no "", with the above code is saving "" in the file. I have tried with
Replace
doesn’t solve.– Matheus Miranda
I think you’re doing the object serialization twice. The first time you assign to
jsonToOutput
, the second you send to the file onSerialize
.– mutlei
The end result is right because it is text. and the bars are escape ...
– novic
@Virgilionovic, in the second time, gives in the line
List<JsonResult> items = JsonConvert.DeserializeObject<List<JsonResult>>(json);
– Matheus Miranda
Error code: 'Error Converting value "[{"Id":0,"Name":"","Address":""},{"Id":1,"Name":"","Address":""}]" to type 'System.Collections.Generic.List`1[EBF.Json+Jsonresult]'. Path '', line 1, position 89.'
– Matheus Miranda
It’s not because of the bars ?
– Matheus Miranda
That way it worked
File.WriteAllText($@"{pathname}\file.json", jsonToOutput);
I think fellow @mutlei is right.– Matheus Miranda