1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSONシリアライズで空白、スペース値の文字列を無視する方法

Posted at

はじめに

CSVファイルのレコード一覧をもとに
APIを使って連携先システムのデータを一括登録・更新したいな~って時ありますよね?

また文字列型の項目にブランクやスペースが入っていた場合、
その値で更新されちゃわないか不安になるときありますよね…?

そんな方のために、
データをシリアライズする際に空白、スペース値が入っている項目を無視する方法を紹介します。
(ただの備忘録です)

サンプルコード

JsonConvert.SerializeObject にオプション情報を追加しました。

        /// <summary>
        /// 文字列をシリアライズ化
        /// </summary>
        /// <typeparam name="T">独自クラスの定義</typeparam>
        /// <param name="obj">文字列</param>
        /// <returns>シリアライズ後の文字列</returns>
        private static string SerializeObject<T>(T obj)
        {
            var settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore, // Null値を無視
                ContractResolver = new CustomContractResolver() // カスタムリゾルバを使用
            };

            return JsonConvert.SerializeObject(obj, settings);
        }

オプションの設定は以下の通りです。

    /// <summary>
    /// シリアライズ化する際のオプション
    /// </summary>
    public class CustomContractResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var property = base.CreateProperty(member, memberSerialization);
            if (property.PropertyType == typeof(string))
            {
                property.ShouldSerialize = instance =>
                {
                    var value = (string)property.ValueProvider.GetValue(instance);
                    return !string.IsNullOrEmpty(value); // 空白、スペース値を無視
                };
            }
            return property;
        }
    }
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?