我正在使用web api返回的JSON结构,但存在问题。Web API返回嵌套的JSON值
说,我有两个表,Teams
和Players
。他们加入了TeamID
(队员和FK玩家PK)。
我希望我的API调用返回如下类似的一些JSON格式:
[
{
TeamId: 1,
TeamName: 'Chicago Bulls',
TeamPlayers: [
{PlayerId: 1, PlayerName: 'Pau Gasol'},
{PlayerId: 2, PlayerName: 'Derrick Rose'},
{PlayerId: 3, PlayerName: 'Joakim Noah'},
{PlayerId: 4, PlayerName: 'Jimmy Butler'},
{PlayerId: 5, PlayerName: 'Taj Gibson'}]
},
{
TeamId: 2,
TeamName: 'Cleveland Cavaliers',
TeamPlayers: [
{PlayerId: 1, PlayerName: 'Lebron James'},
{PlayerId: 2, PlayerName: 'Kyrie Irving'},
{PlayerId: 3, PlayerName: 'Anderson Varejao'},
{PlayerId: 4, PlayerName: 'Dion Waiters'},
{PlayerId: 5, PlayerName: 'Shawn Marion'}]
},
{
TeamId: 3,
TeamName: 'Los Angeles Clippers',
TeamPlayers: [
{PlayerId: 1, PlayerName: 'Chris Paul'},
{PlayerId: 2, PlayerName: 'Blake Griffin'},
{PlayerId: 3, PlayerName: 'DeAndre Jordan'},
{PlayerId: 4, PlayerName: 'Jamal Crawford'},
{PlayerId: 5, PlayerName: 'Matt Barnes'}]
}
]
控制器:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using MyApp.Models;
namespace MyApp.Controllers
{
public class TeamsController : ApiController
{
private DataModel db = new DataModel();
// GET: api/teams
public IQueryable<TeamsWithPlayers> GetTeamsAndPlayers()
{
var query = from x in db.Teams
join y in db.Players on x.TeamId equals y.TeamId
select
{
// This is where I need some help...
}
}
}
}
TeamAndPlayer类:
namespace MyApp.Models
{
public class TeamAndPlayers
{
public int TeamId { get; set; }
public string TeamName { get; set; }
public Players players { get; set; }
}
}
玩家等级:
namespace MyApp.Models
{
public class Players
{
public int TeamId { get; set; }
public int PlayerId { get; set; }
public string PlayerName { get; set; }
}
}
有人可以提供一些见解吗?
您的JSON结构与您的模型不匹配!在JSON中,您返回一组TeamPlayers,而您的TeamAndPlayers拥有一个Player,但名为Players。 – 2014-12-07 10:39:34