0

Is there some way to set what the default representation for null values should be in Json.NET? More specifically null values inside an array.

Given the class

public class Test
{
    public object[] data = new object[3] { 1, null, "a" };
}

Then doing this

Test t = new Test();
string json = JsonConvert.SerializeObject(t);

Gives

{"data":[1,null,"a"]}

Is it possible to make it look like this?

{"data":[1,,"a"]}

Without using string.Replace.

7
  • 4
    No, because {"data":[1,,"a"]} is not a valid json. Commented Nov 2, 2013 at 23:07
  • Why would you want to do that? The result is invalid JSON. If you were the author of a library that produces JSON, would you include an option that makes your library not work correctly on purpose? Commented Nov 2, 2013 at 23:07
  • That's not valid JSON - why would you want it to look that way? Commented Nov 2, 2013 at 23:07
  • @Jon I See. So wouldn't {"data":[1,0,"a"]} be valid Json? Commented Nov 2, 2013 at 23:14
  • @Flunx: It would. But instead of asking a human, hit JSON.parse on your browser console and get a guaranteed correct answer directly. Commented Nov 2, 2013 at 23:16

1 Answer 1

0

Figured it out. I had to implement a custom JsonConverter. As others mentioned this will not produce valid/standard Json.

public class ObjectCollectionConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType ==  typeof(object[]);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        object[] collection = (object[])value;
        writer.WriteStartArray();
        foreach (var item in collection)
        {
            if (item == null)
            {
                writer.WriteRawValue(""); // This procudes "nothing"
            }
            else
            {
                writer.WriteValue(item);
            }
        }
        writer.WriteEndArray();
    }
}

Use it like this

Test t = new Test();
string json = JsonConvert.SerializeObject(t, new ObjectCollectionConverter());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.