反序列化布尔时丢失数据

时间:2019-01-21 15:17:48

标签: c# json.net

我正在尝试将JSON反序列化为一个自制对象A,该对象包含2个字符串和另一个对象B的列表。对象B由另一个字符串和bool组成。

示例JSON:

{  
   "ButtonList":[  
      {  
         "Fast":false,
         "Name":"TableOverview"
      },
      {  
         "Fast":true,
         "Name":"Evaluation"
      }
   ],
   "FavoritGraphic":"PDFreport",
   "FavoritText":"Findings"
}

已对JSON的语法进行了双重检查并正确无误。同样,没有bool的测试也可以。但是,当我尝试使用bool对对象进行反序列化时,List为空(收藏夹字符串仍具有正确的值)。我无法弄清楚我在做什么错...

public class ButtonSettingsModel
{
  public readonly string FavoritText;
  public readonly string FavoritGraphic;
  public readonly List<ButtonInfo> ButtonList;

  public ButtonSettingsModel(string favoritText, string favoritGraphic, List<ButtonInfo> fastButtons)
  {
    FavoritText = favoritText;
    FavoritGraphic = favoritGraphic;
    ButtonList = fastButtons;
  }
}

public class ButtonInfo
{
  public readonly string Name;
  public readonly bool Fast;

  public ButtonInfo(string name, bool fast)
  {
    Name = name;
    Fast = fast;
  }
}

ButtonSettingsModel ButtonSettings = GetObjectFromJson<ButtonSettingsModel>(jsonString);

public T GetObjectFromJson<T>(string jsonString) // correct json
{
  var foo = JsonConvert.DeserializeObject<T>(jsonString); // List == null
  return foo;
}

1 个答案:

答案 0 :(得分:2)

这是关于构造函数参数的命名。虽然不区分大小写,但JSON.Net确实需要将它们匹配。

要么更改json数组名称以匹配构造函数,要么更改构造函数以匹配json:

void Main()
{
    string jsonString = @"{  
   ""buttonList"":[
      {  
         ""Name"":""TableOverview"",
         ""Fast"":false         
      },
      {
         ""Name"":""Evaluation""
      }
   ],
   ""FavoritGraphic"":""PDFreport"",
   ""FavoritText"":""Findings""
}";


    ButtonSettingsModel ButtonSettings = GetObjectFromJson<ButtonSettingsModel>(jsonString);
    //ButtonSettings.Dump();
}

// Define other methods and classes here
public class ButtonSettingsModel
{
    public readonly string FavoritText;
    public readonly string FavoritGraphic;
    public readonly List<ButtonInfo> ButtonList;

    public ButtonSettingsModel(string favoritText, string favoritGraphic, List<ButtonInfo> buttonList)
    {
        FavoritText = favoritText;
        FavoritGraphic = favoritGraphic;
        ButtonList = buttonList;
    }
}

public class ButtonInfo
{
    public readonly string Name;
    public readonly bool Fast;

    public ButtonInfo(string name, bool fast)
    {
        Name = name;
        Fast = fast;
    }
}

public T GetObjectFromJson<T>(string jsonString) // correct json
{
    var foo = JsonConvert.DeserializeObject<T>(jsonString); // List != null
    return foo;
}