Reputation: 393
I have a function that connects to the database and executes a query and returns the data, now I am trying to call that function and convert the data to JSON
public List<string> getListItems()
{
AirportClass airport = new AirportClass();
return JArray.Parse(airport.getListItems());
return airport.getListItems();
}
I keep getting this error 'The best overloaded method match for 'Newtonsoft.Json.Linq.JArray.Parse(string)' has some invalid arguments'
What am I doing wrong?
I have also tried the following:
public List<string> getListItems()
{
AirportClass airport = new AirportClass();
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
JsonConvert.Serialize(airport.getListItems());
return JsonConvert;
}
but this also gives me an error 'Cannot implicitly convert type 'JavaScriptSerializer' to Generic.List'
I also tried:
public List<string> getListItems()
{
AirportClass airport = new AirportClass();
JsonSerializer JsonConvert = new JsonSerializer();
JsonConvert.Serialize(getListItems());
return airport.getListItems();
}
but this gives me another error 'No overload for method 'Serialize' takes 1 arguments'
Upvotes: 2
Views: 15898
Reputation: 38367
You are not saving the return of the Serialize result:
JsonConvert.Serialize(airport.getListItems());
return JsonConvert;
Corrected with correct return type. Converting from object to JSON produces a single string encoded as a JSON array, so your return type is string
, not List<string>
public string getListItems() {
AirportClass airport = new AirportClass();
//removed JsonConvert declaration cause that would hide the JsonConvert class, don't name variables the same name as classes
string result = JsonConvert.SerializeObject(airport.getListItems());
return result;
}
It does not produce a List, to do that you'd need to serialize each item seperately, which is different from serializing a list. In that case you'd just use a loop to call Serialize on each item.
Upvotes: 3