2017-02-16 1 views
2

からNULLを返すために、私はクラスを持っている:どのようJsonConvert.DeserializeObject

public class CustomResponse 
{ 
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public string Message {get; set; } 
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public string Details {get; set; } 
} 

それから私は、このクラスにJSON文字列をデシリアライズしようとしています。たとえば

var settings = new JsonSerializerSettings 
    { 
     NullValueHandling.Ignore, 
     MissingMemberHandling.Ignore, 
    }; 
var customResponse = JsonConvert.Deserialize<CustomResponse>(jsonString, settings); 

私のJSON文字列:

{"DocumentId":"123321", "DocumentNumber":"ABC123"} 

結果として、すべてのプロパティがNULLであるオブジェクトがありますが、customResponseはNULLではありません。どのように結果にNULLを取得するのですか?

+1

のような多相コンバータを使用することを検討してください。[カスタム 'JsonConverter'](http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm )そのために。 – dbc

+0

使用しているJSON文字列を追加できますか? – Zinov

+0

なぜ 'customResponse'が' null'になると思いますか? –

答えて

1

あなたのオブジェクトを割り当て、移入custom JsonConverterを作成することができ、その後、すべてのプロパティがnullであるかどうかを確認するために、JsonProperty.ValueProvider

によって返された値を使用してチェックします。

var settings = new JsonSerializerSettings 
{ 
    NullValueHandling = NullValueHandling.Ignore, 
    MissingMemberHandling = MissingMemberHandling.Ignore, 
    Converters = { new ReturnNullConverter<CustomResponse>() }, 
}; 
var customResponse = JsonConvert.DeserializeObject<CustomResponse>(jsonString, settings); 

サンプルfiddleを:

はそれが好きで使用しています。

しかし、あなたが書いたコメントでは、CustomResponseがNULLの場合は、サービスは正しい応答を返し、私はOtherCustomResponseにデシリアライズしようとします。その場合は、How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?またはDeserializing polymorphic json classes without type information using json.net

1

カスタムJsonConverterを作成しないようにしたい場合は、次の拡張メソッドを使用することができます。

public static class Exts 
{ 
    public static T OrDefaultWhen<T>(this T obj, Func<T, bool> predicate) 
    { 
     return predicate(obj) ? default(T) : obj; 
    } 
} 

は使用方法:

var jsonString = @"{ 
    Message: null, 
    Details: null 
}"; 

var res = JsonConvert.DeserializeObject<CustomResponse>(jsonString) 
        .OrDefaultWhen(x => x.Details == null && x.Message == null); 
+0

それも働いてくれてありがとう、私はもっと好きな別のオプション –