Reputation:
I have to return data in json format but it says cannot implicitly convert type string to 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
}
I tried tostring() and many other ways but nothing worked. How can I convert string to object?
Here is my function code 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>();
}
}
}
Upvotes: 1
Views: 2133
Reputation:
here is configuration settings
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);
}
}
}
Upvotes: 1
Reputation: 463
this code helps me to solve both api and kendo problem
[HttpGet]
public List<object> GetAllCompanies2()
{
List<object> myCo = DefCompany.AllDefCompany2;
object json = JsonConvert.SerializeObject(myCo);
return json;
}
Upvotes: 2
Reputation: 41
[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
}
Try this. Need to change function return type based on whether you return list of objects or string (in this case json)
Upvotes: 0
Reputation: 298
You can convert string
to object
, but what you are trying to do in the code shown is convert it to a List<object>
. You can try calling AsEnumerable
or ToList
on the json
variable.
But if what you want to do is return a string, why not change the return type of the method?
Upvotes: 0