如果设置的值为null,如何将类中的字段设置为false?

时间:2014-07-22 06:36:25

标签: c# json deserialization

我有以下内容:

var result2 = result1
          .Select((t, index) => new  {
             Answer = t.Answer,
             Answers = JSON.FromJSONString<Answer2>(t.AnswerJSON)
          });
          return Ok(result2);

    public class Answer2 {
        public bool? Correct; // Maybe this should be a property
        public bool Response; // Maybe this should be a property
    }

我的字符串&gt;对象功能:

    public static T FromJSONString<T>(this string obj) where T : class
    {
        if (obj == null)
        {
            return null;
        }
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            T ret = (T)ser.ReadObject(stream);
            return ret;
        }
    }

如果JSON字符串中的Response存在null或者JSON字符串中的Response没有值,我是否可以使Response字段为false?

注意:我有一个关于使用房产的建议,我认为这样可行,但我不确定如何在实践中这样做。

2 个答案:

答案 0 :(得分:6)

你应该使用一个属性:

public class Answer2 {
    private bool correct;  // This field has no need to be nullable
    public bool? Correct
    {
        get { return correct; }
        set { correct = value.GetValueOrDefault(); }
    }

}

答案 1 :(得分:1)

在Q和A部分之后,您应该可以在以下属性上执行此操作:

private bool? whatever;
public bool? Whatever
{
   get { return whatever; }
   set
   {
       if (value == null)
          whatever = false;
       else
          whatever = value;
   }
}

这样您就可以将null值传递给属性,但它只能包含bool(true / false)值。

相关问题