我正在使用ApiController,我无法接受调用以返回除XML之外的任何内容。
class CountryCatalogue(Country):
def __init__(self, filename = "", name = "", pop = 0, area = 0, continent = ""):
cDictionary = {} #Initializing the cDictionary and catalogue here leads to errors in other functions
catalogue = []
super().__init__(name = "",pop = 0,area = 0,continent = "")
fillcdict = open("continent.txt") #not really important for the problem
linescdict = fillcdict.readlines()[1:]
for line in linescdict:
entries1 = line.split(",")
country = str(entries1[0])
continentwrong = str(entries1[1])
entries2 = continentwrong.split ("\n")
continent = str(entries2[0])
cDictionary["keywords"] = country
cDictionary["values"] = continent
self._continent = continent
fillcatdict = open(filename)
linescatalogue = fillcatdict.readlines()[1:]
for line in linescatalogue:
entries = line.split("|")
countrydata = str(entries[0])
populationdata = entries[1]
areadata = entries[2]
catalogue.append(countrydata)
def findCountry(self): #So, when I try and use catalogue in this function I get a 'unresolved reference' note in Pycharm and a "invalid variable' error if I run the problem
findcountinp = input("Please enter a country name: ")
if findcountinp in catalogue:
return self._name+"|"+self._continent+"|"+self._area+"|"+self._population
else:
return "Country not found!"
理想情况下,我想正常返回JSON,但我决定返回原始字符串而不是XML包装。
答案 0 :(得分:3)
确保api仅返回JSON的一种简单方法是从http配置中删除xml格式化程序。
您可以访问WebApiConfig类
中的格式化程序public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//Clear current formatters
config.Formatters.Clear();
//Add only a json formatter
config.Formatters.Add(new JsonMediaTypeFormatter());
}
}
<强>更新强>
不要序列化控制器中的对象。只需按原样返回对象即可。 Web api将为您执行此操作,因为您已将json格式化程序附加到配置中。
public class GuideController : ApiController
{
[AcceptVerbs("GET")]
[HttpGet]
public IHttpActionResult Get()
{
Item item = Item.GetTestData();
return Ok(item);
}
}
答案 1 :(得分:0)
尝试在客户端中设置Accept标头。如果要接收JSON,请设置
接受:application / json
在您的客户端。希望有所帮助。
答案 2 :(得分:0)
尝试显式返回JSON。
[HttpGet]
public IHttpActionResult Get()
{
Item item = Item.GetTestData();
return Json(item);
}