Skip to main content
 首页 » 编程设计

c#之如何为 web api 返回对象格式的数据

2024年06月20日42hnrainll

我必须以 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 
    } 

我尝试了 tostring() 和许多其他方法,但没有任何效果。如何将字符串转换为对象?
这是我的函数代码 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 和 kendo 问题

[HttpGet] 
public List<object> GetAllCompanies2() 
{ 
    List<object> myCo = DefCompany.AllDefCompany2;          
 
    object json = JsonConvert.SerializeObject(myCo); 
    return  json; 
}