如何为web api返回对象格式的数据
本文关键字:对象 格式 数据 返回 api web | 更新日期: 2023-09-27 17:50:53
我必须以json格式返回数据,但它表示无法将类型字符串隐式转换为system.collection.generic.list(object(.
[HttpGet]
public List<object> GetAllCompanies2()
{
List<object> myCo = DefCompany.AllDefCompany2;
// return myCo----------> works
string json = JsonConvert.SerializeObject(myCo);
return json; ------- > not works conversion error & i need this
}
我试着字符串((和其他很多方法,但都没用。如何将字符串转换为对象
这是我的功能代码AllDefCompany2
public static List<object> AllDefCompany2
{
get
{
using (var db = new RPDBEntities())
{
return db.DefCompanies.Select(b => new
{
Id = b.Id,
CurrentCurrencyCode = b.CurrentCurrencyCode,
ShortName = b.ShortName,
FullName = b.FullName,
ContactPerson = b.ContactPerson,
Address1 = b.Address1,
CompanyCity = b.CompanyCity,
CompanyState = b.CompanyState,
CompanyCountry = b.CompanyCountry,
ZipPostCode = b.ZipPostCode,
TelArea = b.TelArea
}).ToList<object>();
}
}
}
这段代码帮助我解决了api和剑道问题
[HttpGet]
public List<object> GetAllCompanies2()
{
List<object> myCo = DefCompany.AllDefCompany2;
object json = JsonConvert.SerializeObject(myCo);
return json;
}
这里是配置设置
using System.Data.Entity;
namespace RpManticSolAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
}
}
return JsonConvert.SerializeObject(myCo);
您可以将string
转换为object
,但您在所示代码中要做的是将其转换为List<object>
。您可以尝试对json
变量调用AsEnumerable
或ToList
。
但是,如果您想返回一个字符串,为什么不更改该方法的返回类型呢?
[HttpGet]
public string GetAllCompanies2()
{
List<object> myCo = DefCompany.AllDefCompany2;
// return myCo----------> works
string json = JsonConvert.SerializeObject(myCo);
return json; ------- > not works conversion error & i need this
}
试试这个。需要根据返回对象列表还是字符串(在本例中为json(