-1

Array like this:

var arr = new object[] {0, string.Empty, null};

serializes by JSON.NET to:

[0,"",null]

I need to force JSON.NET to get next result (no value at all for type defaults):

[,,]

Is there any way to archieve this?

AsValeO
  • 2,859
  • 3
  • 27
  • 64

1 Answers1

2
public static class JsonHelper
    {
        public static string SerializeToMinimalJson(object obj)
        {
            return JToken.FromObject(obj).RemoveEmptyChildren().ToString();
        }

        public static JToken RemoveEmptyChildren(this JToken token)
        {
            if (token.Type == JTokenType.Object)
            {
                JObject copy = new JObject();
                foreach (JProperty prop in token.Children<JProperty>())
                {
                    JToken child = prop.Value;
                    if (child.HasValues)
                    {
                        child = child.RemoveEmptyChildren();
                    }
                    if (!child.IsNullOrEmpty())
                    {
                        copy.Add(prop.Name, child);
                    }
                }
                return copy;
            }
            else if (token.Type == JTokenType.Array)
            {
                JArray copy = new JArray();
                foreach (JToken item in token.Children())
                {
                    JToken child = item;
                    if (child.HasValues)
                    {
                        child = child.RemoveEmptyChildren();
                    }
                    if (!child.IsNullOrEmpty())
                    {
                        copy.Add(child);
                    }
                }
                return copy;
            }
            return token;
        }

        public static bool IsNullOrEmpty(this JToken token)
        {
            return token == null ||
                   (token.Type == JTokenType.Array && !token.HasValues) ||
                   (token.Type == JTokenType.Object && !token.HasValues) ||
                   (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
                   (token.Type == JTokenType.Null);
        }

    }

Above class will remove the empty children. You can then serialize your object(s) like this:

var json = JsonHelper.SerializeToMinimalJson(obj);
Suhel Patel
  • 278
  • 1
  • 12
  • https://stackoverflow.com/questions/36884902/how-to-omit-ignore-skip-empty-object-literals-in-the-produced-json/36902293#36902293 – lnu Sep 03 '20 at 16:16