我有一个JSON对象进入Web API中的控制器,该控制器没有绑定到我的模型。我正在使用Fiddler测试它,身体中有以下JSON:
{
"userList": {
"user": [
{
"custCode": "test1",
"userName": "TheDude",
"admin": "false",
"effectiveDate": "2/14/2014"
},
{
"custCode": "test1",
"userName": "Bob",
"admin": "false",
"effectiveDate": "2/14/2014"
},
{
"custCode": "test1",
"userName": "Ted",
"admin": "false",
"effectiveDate": "2/14/2014"
},
{
"custCode": "test1",
"userName": "Darryl",
"admin": "false",
"effectiveDate": "2/14/2014"
}
]
}
}
我已经包含了为模型和控制器方法构建的类。
public class UserList
{
public List<User> userList { get; set; }
}
public class User
{
public string custCode { get; set; }
public string userName { get; set; }
public bool admin { get; set; }
public DateTime effectiveDate { get; set; }
}
[HttpPost]
public void CreateNewUser(UserList newUsers)
{
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
conn.Open();
try
{
foreach (var user in newUsers.userList)
{
//SQL code is here
}
}
finally
{
conn.Close();
conn.Dispose();
}
}
它挂在foreach循环上,给我一个“对象引用未设置为对象的实例”错误。我注意到,当它第一次命中方法时,UserList对象为null。我很欣赏有关我做错的任何观察。
答案 0 :(得分:1)
通过执行以下操作解决了问题:
我将UserList类更改为字符串数组:
public class UserList
{
public User[] users { get; set; }
}
然后我重新格式化了我的请求主体JSON:
{
"users": [
{
"custCode": "test1",
"userName": "TheDude",
"admin": "false",
"effectiveDate": "2/14/2014"
},
{
"custCode": "test1",
"userName": "Bob",
"admin": "false",
"effectiveDate": "2/14/2014"
},
{
"custCode": "test1",
"userName": "Ted",
"admin": "false",
"effectiveDate": "2/14/2014"
},
{
"custCode": "test1",
"userName": "Darryl",
"admin": "false",
"effectiveDate": "2/14/2014"
}
]
}
在更改之后,我使用Fiddler进行了重新测试,一切正常。
答案 1 :(得分:0)
应该是这样的:
public class OuterClass
有一个private UserList userList
,然后又有一个名为:
public class UserList
有一个private List<User> user
基本上:
public class OuterClass
{
private UserList userList {get; set; }
}
public class UserList
{
private List<User> user {get; set; }
}
如果您认为JSON中的某些键名称命名错误,即使我这么认为。