2014-10-20 2 views
0

У меня есть следующий Asp.Net 4.5 Web метод Api:Как вернуть JSON массив в объекте контейнера

public IEnumerable<RCWindsWCFService.uspGetAllStationsResult> GetExtAllStations() 
{ 
    RCWindsWCFService.Service1Client client = new RCWindsWCFService.Service1Client(); 
    IEnumerable<RCWindsWCFService.uspGetAllStationsResult> results = client.GetExtAllStations(); 
    return results; 
} 

Это возвращает следующие результаты JSON:

[{POINT_X: -81.0410610591, POINT_Y: +34,1831858023, TABLE_NAME: "Cedar Creek"}, {POINT_X: -80.7653777161, POINT_Y: 33.8641198907, TABLE_NAME: "Gadsden"}]

Что мне нужно вернуться в:

{Station_Coordinates: [{PO INT_X: -81,0410610591, POINT_Y: +34,1831858023, TABLE_NAME: "Cedar Creek"}, {POINT_X: -80.7653777161, POINT_Y: 33.8641198907, TABLE_NAME: "Gadsden"}]}

Поскольку я очень новой для этих технологий, я бы ценят предложения относительно того, как это может быть достигнуто. Если возможно, рекомендуются конкретные рекомендуемые изменения вышеприведенного кода.

Спасибо

Чтобы улучшить форматирование в моем ответе на @LB комментарий ниже я вновь разместить его:

public IEnumerable<RCWindsWCFService.uspGetAllStationsResult> GetExtAllStations() 
    { 
     RCWindsWCFService.Service1Client client = new RCWindsWCFService.Service1Client(); 
     StationCoordinates coordinates = new StationCoordinates(); 
     IEnumerable<RCWindsWCFService.uspGetAllStationsResult> results = client.GetExtAllStations(); 
     coordinates.Station_Coordinates = results; 
     return coordinates; 
    } 

    class StationCoordinates 
    { 
     public IEnumerable<RCWindsWCFService.uspGetAllStationsResult> Station_Coordinates { set; get; } 
    } 

Я теперь получать: Не удается неявно преобразовать «RCWindsExtSvc.Controllers типа .RCWindsExtSvcController.StationCoordinates 'to' System.Collections.Generic.IEnumerable '. Явное преобразование существует (вы пропускаете листинг?) - Я бы заподозрил неправильное использование с моей стороны.

Еще раз заблаговременно.

Update:

код был изменен, чтобы отразить комментарий Moby диска, как показано ниже:

public IEnumerable<StationCoordinates> GetExtAllStations() 
    { 
     RCWindsWCFService.Service1Client client = new RCWindsWCFService.Service1Client(); 
     StationCoordinates coordinates = new StationCoordinates(); 
     //IEnumerable<coordinates> results = client.GetExtAllStations(); 
     IEnumerable<RCWindsWCFService.uspGetAllStationsResult> results = client.GetExtAllStations(); 
     coordinates.Station_Coordinates = results; 

     return coordinates; 
    } 

    class StationCoordinates 
    { 
     public IEnumerable<RCWindsWCFService.uspGetAllStationsResult> Station_Coordinates { set; get; } 
    } 

Код ошибки остается:

Не может неявно преобразовать тип «RCWindsExtSvc.Controllers.RCWindsExtSvcController. StationCoordinates 'to' System.Collections.Generic.IEnumerable '. Явное преобразование существует (вы пропали без вести бросок?)

+3

Создайте класс со свойством 'public IEnumerable Station_Coordinates {set; get;} 'и вернуть его. –

+0

Спасибо, L.B - моя проблема теперь заключается в использовании (опять же, новизне технологий). Мой код выглядит следующим образом: – DFuller

+0

@ L.B: извините за форматирование. Ошибка: Невозможно неявно преобразовать тип «RCWindsExtSvc.Controllers.RCWindsExtSvcController.StationCoordinates» в «System.Collections.Generic.IEnumerable ». Явное преобразование существует (вы пропускаете листинг? – DFuller

ответ

0

ответ LB, кажется, работает очень хорошо для меня:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 

namespace Server.Controllers 
{ 
    public class TempController : ApiController 
    { 
     public StationCoordinates GetExtAllStations() 
     { 
      RCWindsWCFService.Service1Client client = new RCWindsWCFService.Service1Client(); 
      StationCoordinates coordinates = new StationCoordinates(); 
      IEnumerable<RCWindsWCFService.uspGetAllStationsResult> results = client.GetExtAllStations(); 
      coordinates.Station_Coordinates = results; 
      return coordinates; 
     } 

     public class StationCoordinates 
     { 
      public IEnumerable<RCWindsWCFService.uspGetAllStationsResult> Station_Coordinates { set; get; } 
     } 

    } 
} 

namespace RCWindsWCFService 
{ 
    public class uspGetAllStationsResult 
    { 
     public double POINT_X { get; set; } 
     public double POINT_Y { get; set; } 
     public string TABLE_NAME { get; set; } 
    } 

    public class Service1Client 
    { 
     public IEnumerable<uspGetAllStationsResult> GetExtAllStations() 
     { 
      return new List<uspGetAllStationsResult>() 
      { 
       new uspGetAllStationsResult() {POINT_X= -81.0410610591,POINT_Y= 34.1831858023,TABLE_NAME= "Cedar Creek"}, 
       new uspGetAllStationsResult() {POINT_X= -80.7653777161,POINT_Y= 33.8641198907,TABLE_NAME= "Gadsden"} 
      }; 
     } 
    } 
} 

Выход JSON из выше:

{"Station_Coordinates":[{"POINT_X":-81.0410610591,"POINT_Y":34.1831858023,"TABLE_NAME":"Cedar Creek"},{"POINT_X":-80.7653777161,"POINT_Y":33.8641198907,"TABLE_NAME":"Gadsden"}]}

Который я верю, это то, что вы хотели.

+0

Да, вы абсолютно правы, и я не могу поблагодарить вас за вашу настойчивость! Благодаря вашему симуляционному коду я могу теперь выделить то, что характерно для моей среды. Еще раз спасибо вам и L.B. – DFuller

Смежные вопросы