How to insert new object in json file

Asked

Viewed 997 times

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

  • What is the difference between the result obtained and the expected?

  • @LINQ In the original file is no "", with the above code is saving "" in the file. I have tried with Replace doesn’t solve.

  • I think you’re doing the object serialization twice. The first time you assign to jsonToOutput, the second you send to the file on Serialize.

  • 1

    The end result is right because it is text. and the bars are escape ...

  • @Virgilionovic, in the second time, gives in the line List<JsonResult> items = JsonConvert.DeserializeObject<List<JsonResult>>(json);

  • 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.'

  • It’s not because of the bars ?

  • That way it worked File.WriteAllText($@"{pathname}\file.json", jsonToOutput); I think fellow @mutlei is right.

Show 4 more comments

2 answers

2

From what I understand you’re getting one json, playing in a list, adding a new item, converting again to json and saving.

For 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 and so you can save that you will not "catch" the escapes

I also left in the .Netfiddle for reference

1


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

So much here:

jsonToOutput = JsonConvert.SerializeObject(items);

How much here:

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

The problem is that in the last line, it is Serializing an already serialized object. Soon the string formed in the second serialization is the first with the correct formatting all escaped (with a \" which prevents normal interpretation of quotation marks (")).

So, it’s time to write the serialized object.

File.WriteAllText($@"{pathname}\file.json", jsonToOutput);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.