简体   繁体   中英

JSON.NET serialize array with empty string for default values

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM