0

I'm trying to write a JSON file in C#, and I have a problem where I want to seperate each object with a comma (',') for it to be valid JSON, however I can't figure out how to do this. I've searched if there is a way you can search for a specific pattern in a string (in my case it would be '}{') and a regular expression might work, but I don't know how to create one.

The final result should look like

      '},{'

instead of

      '}{'.

Here is my code so far:

    private void loopThroughArray()
    {
        string json = "";
            for (int i = 0; i < array.Count; i++)
            {
                MyObject t = array[i];
                json += new JavaScriptSerializer().Serialize(t);
                //this writes the json to the file but without comma seperator
            }

        System.IO.File.WriteAllText(@"<MyFilepath>\json.txt", "{\"json\":[" + json + "]}");
       //this writes the json to a file that and is in a json array called 'json' 

    }
kg98
  • 47
  • 9
  • 1
    Why are you writing your own JSON serializer? Should use something like http://www.newtonsoft.com/json if you can. – Measurity Jun 24 '17 at 01:28
  • I'll look at the Newtonsoft one, I know its good for deserialisation. I thought the JavaScriptSerializer was as good as I would get. – kg98 Jun 24 '17 at 01:32

7 Answers7

1

I looked at different ways of serialising JSON as per @Measuring 's suggestion and discovered that this was the easiest method in my opinion:

    json = JsonConvert.SerializeObject(MyObject);

Works perfectly, thanks @Measuring!

kg98
  • 47
  • 9
1

I agree with @Measuring it seems like an over complication to write your own when there are tools which can be used as identified in this answer.

Nonetheless you could do the following...

string json = "";
for (int i = 0; i < array.Count; i++){
    MyObject t = array[i];
    json += new JavaScriptSerializer().Serialize(t);
}

string pattern = "\}{\";
string replacement = "},{";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(json, replacement);
Zze
  • 18,229
  • 13
  • 85
  • 118
1

What you are trying to do can be solved by string.Join and a bit of Linq

var serializer = new JavaScriptSerializer();
var json = string.Join( ",", array.Select( e => serializer.Serialize(e) );
Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
0

Looks like this:

json += new JavaScriptSerializer().Serialize(t);

Is creating a {json object}. Your solution might be as easy as appending a , after like:

json += new JavaScriptSerializer().Serialize(t) + ",";

Edit (responding on your comment):
You can easily skip the last loop with an inner check.

json += new JavaScriptSerializer().Serialize(t);
if (i < array.Count - 1) json += ",";

Alternatively you could cut the for-loop 1 item short and add the last item after the loop.

Measurity
  • 1,316
  • 1
  • 12
  • 24
0

It's far more efficient to use a StringBuilder than += and you should avoid creating reusable objects within loops.

Keeping as close to your code as possible, you could try:

private void loopThroughArray()
{
   var serializer = new JavaScriptSerializer();
   var json = new System.Text.StringBuilder();
   for (int i = 0; i < array.Count; i++)
   {
      MyObject t = array[i];
      json.Append(serializer.Serialize(t));
      if (i < array.Count)
         json.Append(",");
   }
   System.IO.File.WriteAllText(@"<MyFilepath>\json.txt", "{\"json\":[" + json.ToString() + "]}");
}

But it may be simpler to try:

private void loopThroughArray()
{
   var serializer = new JavaScriptSerializer();
   var json = serializer.Serialize(array);
   System.IO.File.WriteAllText(@"<MyFilepath>\json.txt", "{\"json\":" + json.ToString() + "}");
}

But, if I were doing it I'd use Json.Net's JsonConvert on an anonymous type:

System.IO.File.WriteAllText(
    @"<MyFilepath>\json.txt",
    JsonConvert.SerializeObject(new {
        json = array
    }));

You can get Json.Net from nuget.

Rob
  • 141
  • 1
  • 9
0

JsonNet is indeed easier to use, but in your case it feels like JavaScriptSerializer works fine. Presumably you expect "{json:[...]}" as result - serializing new {json = array} instead of just array will produce that output:

var finalJson = new JavaScriptSerializer().Serialize(new {json = array});

Side note: please avoid manual string manipulation when constructing JSON or XML -it is not worth the effort and result in most cases is somewhat wrong.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
-1

Hi Kevin would it not be possible to replace the string using regex expressions,

/}{/g

and replace with

},{
Johann Nel
  • 176
  • 5