我有以下脚本
<script>
$(window).load(function () {
var model = [
{
"reservation":
{
"ticketId": "782274b8-10d9-444c-8f05-3117853e3ee0",
"clubId": 70656,
"courtNumber": 1,
"crud_name": "add",
"reservationtype_name": "toernooi",
"players" :
[
{
"player" : { "id": "18674992", "name": "Jan Jansen"}
},
{
"player": { "id": "19543840", "name": "Klaas Klaassen" }
}
]
}
},
{
"reservation":
{
"ticketId": "782274b8-10d9-444c-8f05-3117853e3ee0",
"clubId": 70656,
"courtNumber": 1,
"crud_name": "update",
"reservationtype_name": "toernooi",
"players":
[
{
"player": { "id": "18674992", "name": "Jan Jansen" }
},
{
"player": { "id": "19543840", "name": "Klaas Klaassen" }
}
]
}
}
];
alert(JSON.stringify(model));
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "http://localhost:59854/api/incomingapi",
contentType: "application/json",
dataType: 'json',
success: function (result) { },
error: function (errResult) { }
});
});
</script>
我有这些课程
namespace MySQLTestApp.Models
{
public class player
{
public string id { get; set; }
public string name { get; set; }
}
public class ReservationModelForJson
{
public string ticketId { get; set; }
public int clubId { get; set; }
public int courtNumber { get; set; }
public string crud_name { get; set; }
public string reservationtype_name { get; set; }
public IEnumerable<player> players { get; set; }
}
public class JsonBinder
{
public ReservationModelForJson reservation { get; set; }
}
}
这是我的控制器
public string Post(IEnumerable<JsonBinder> reservations)
{
int clubId = reservations.First().reservation.clubId;//is 70656
int courtNumber = reservations.First().reservation.courtNumber;//is 1
string playerId = reservations.First().reservation.players.First().id;//is null, should be 18674992
return "tnkx!";
}
&#39;&#39;&#39; players
中reservation
的{{1}}财产不会被填充。所有简单的价值观都有!如您所见,clubId
和courtNumber
都有值。
我无法改变Json的格式。我必须创建一个正确的类结构。并使用它来解析值...
有人知道要创建的正确的类结构吗?我无法解决这个问题......
答案 0 :(得分:0)
根据你的模型你应该有某种PlayerWrapper:
public class playerWrapper
{
public player player{ get; set; }
}
public class player
{
public string id { get; set; }
public string name { get; set; }
}
public class ReservationModelForJson
{
...
public IEnumerable<playerWrapper> players { get; set; }
}
public class JsonBinder
{
public ReservationModelForJson reservation { get; set; }
}
答案 1 :(得分:0)
您可以使用json2csharp.com从JSON生成类。
你应该:
public class Player2
{
public string id { get; set; }
public string name { get; set; }
}
public class Player
{
public Player2 player { get; set; }
}
public class Reservation
{
public string ticketId { get; set; }
public int clubId { get; set; }
public int courtNumber { get; set; }
public string crud_name { get; set; }
public string reservationtype_name { get; set; }
public List<Player> players { get; set; }
}
public class RootObject
{
public Reservation reservation { get; set; }
}