Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

json add new object to existing json file C#

I'm trying to automate the adding of new objects to an existing json file. I looked all around the web but only found adding data and stuff but not an whole object. This is how the file that i wanna edit looks:

[
    {"id":"123","name":"carl"}
]

and i want to go to

[
     {"id":"123","name":"carl"},
     {"id":"1234","name":"carl2"}
]

Thank you for all your answers but i don't think everyone is completely understanding what i mean i have tried some of the answers but then i get this:

[
    "{"id":"123","name":"carl"}"
]"{"id":"1234","name":"carl2"}"

and i want everthing inbetween the [].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you use json.NET you can simply deserialize and serialize the json.

var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);
list.Add(new Person(1234,"carl2");
var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...