2

I recently realized that serializing arrays with both Json.NET and Jil libraries, results a wrong JSON object! at least as far as https://jsonlint.com says. For example

var serializer = // Json.NET_Serializer or Jil_Serializer;
var json = serializer.Serialize(new[] {1,2,3,4,5});
Console.WriteLine(json);

results { [1, 2, 3, 4, 5] } which as https://jsonlint.com (and also https://jsonformatter.curiousconcept.com/) says, is wrong

// The error message in jsonformatter:

Expecting string or }, not [.

and expected result I think is:

[1, 2, 3, 4, 5]

Is there any hidden point which I missed? For example is there any special setting in Json.NET or Jil to solve this problem?

UPDATE: Note that the question is not how to achieve the mentioned result. But is about how to get JSON.NET or JIL to work right. Thanks in advance.

Community
  • 1
  • 1
amiry jd
  • 27,021
  • 30
  • 116
  • 215

3 Answers3

1

No idea what you're doing wrong, but with the following code using JSON.Net:

using System;
using System.IO;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var json = JsonConvert.SerializeObject(new[] {1,2,3,4,5});

        Console.WriteLine(json);

        JsonSerializer serializer = new JsonSerializer();

        using (StringWriter sw = new StringWriter())
        using (JsonWriter writer = new JsonTextWriter(sw))
        {
            serializer.Serialize(writer, new[] {1,2,3,4,5});

            Console.WriteLine(sw);
        }
    }
}

I get the correct output with both JsonConvert.SerializeObject() and JsonSerializer.Serialize() (fiddle here):

[1,2,3,4,5]
[1,2,3,4,5]
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

You could try using JavScriptSerializer, like so -

new JavaScriptSerializer().Serialize(new[] {1,2,3,4,5});

That produces the expected result for me.

Reeseoo
  • 59
  • 4
0

Using JArray.FromObject() works fine for me:

Console.WriteLine(JArray.FromObject(new[] {1,2,3,4,5}));
Just Shadow
  • 10,860
  • 6
  • 57
  • 75