How to insert new object into json file

0

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?

    
asked by anonymous 15.05.2018 / 21:42

2 answers

1

According to the comments (with the input of the response author), the error was that the object was being serialized twice.

Both here:

jsonToOutput = JsonConvert.SerializeObject(items);

How much here:

JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, jsonToOutput);

The problem is that in the last line, you are serializing an object already serialized. So the string formed in the second serialization is the first one with the correct formatting every escape (with a \" that prevents the normal interpretation of the quotation marks ( " )).

So it's time to write the serialized object.

File.WriteAllText($@"{pathname}\file.json", jsonToOutput);
    
15.05.2018 / 22:46
2

So I understand you are getting a json , playing in a list, adding a new item, converting back to json and saving.

To do this, just do the SerializeObject of the list,

string json = "[{\"Id\":0,\"Nome\":\"\",\"Endereco\":\"\"},{\"Id\":1,\"Nome\":\"\",\"Endereco\":\"\"}]";
List<JsonResult> items = JsonConvert.DeserializeObject<List<JsonResult>>(json);

var last = items[items.Count - 1].Id + 1;

items.Add(new JsonResult()
{
    Id = last,
    Nome = "Leonardo",
    Endereco = "Rua de baixo"
});

string myJsonOutput = JsonConvert.SerializeObject(items);

The variable myJsonOutput will generate a string json so you can save that it will not "catch" the escapes

I also left the .NetFiddle for reference

    
15.05.2018 / 22:48