I'm new in Json, already searching many info but no luck, based on:
json add new object to existing json file C# - Stack Overflow[
^] (have tried it, and it's works)
But that needs an array json format (begin with
[ , ends with
]), mine is object json format (begin with
{ , ends with
}).
So, how to do that in
Newtonsoft.Json without change the json into Json array format?
my Json (object):
{
"Group": "Group1",
"ID": 1,
"Name": "Author1",
"Description": "Desc1"
}
Using this to create it:
class Author
{
public string Group { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
private Author NewAuthor()
{
Author author = new Author()
{
Group = "Group1",
ID = 1,
Name = "Author1",
Description = "Desc1"
};
return author;
}
private void Btn_Create_Click(object sender, EventArgs e)
{
string jsonData = JsonConvert.SerializeObject(NewAuthor(), Formatting.Indented);
File.WriteAllText(Filepath, jsonData);
}
Desired output:
{
"Group": "Group1",
"ID": 1,
"Name": "Author1",
"Description": "Desc1"
},
{
"Group": "Group2",
"ID": 2,
"Name": "Author2",
"Description": "Desc2"
}
What I have tried:
Based on
json add new object to existing json file C# - Stack Overflow[
^]
below code works, but when the json begin with
[ not
{
Author author = NewAuthor();
var lst = JsonConvert.DeserializeObject<List<Author>>(json) ?? new List<Author>();
lst.Add(author);
string updatedJson = JsonConvert.SerializeObject(lst, Formatting.Indented);
File.WriteAllText(filepath, updatedJson);