Mike Diaz
Mike Diaz

Reputation: 2065

JSON.NET For loop, WriteObject

I have a schema that i write like this

 foreach (var misModel in r)
            {
                writer.WriteStartObject();


                SaveModel(misModel, writer);


               writer.WriteEndObject();    

            }

The problem I am having is my data shows up like this

[{data:1, test:2}{data:2,test:1}]

Notice that there is no comma between the two objects. How would I tell JSON.NET that I am writing a new object within the array.

Upvotes: 0

Views: 142

Answers (1)

evanmcdonnal
evanmcdonnal

Reputation: 48076

You don't have to! All of that work is needless. Instead just do;

string json = JsonConvert.SeralizeObject(r);

If you pass SerializeObject a list or array of objects it will correctly create an array of json objects. If you're trying to write to a file - which it appears you are - then you could just do File.WriteAllText(@".\myJson", json); Or even make it all one line;

File.WriteAllText(@".\myJson", JsonConvert.SerializeObject(r));

Upvotes: 2

Related Questions