我正在构建一个Web API,该API异步调用Odata端点。 odata端点返回JSON,我也试图从Web API返回相同的JSON。由于我异步调用Odata端点,因此我使用Task作为API方法的返回类型,但我想将它们作为JSON返回,我不确定如何做到这一点。下面是我的代码
public async Task<string> GetEmployee(string instance)
{
.....
EmployeeDTO.RootObject returnObj = new EmployeeDTO.RootObject();
var responsedata = "";
try
{
using (var client_Core = new HttpClient())
{
....
string core_URL = BaseURL_Core+URL_instance;
var response = client_Core.GetAsync(core_URL).Result;
responsedata = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
throw ex;
}
return responsedata;
当前它返回为
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{
"@odata.context":"https://science.com/odata/$metadata#EMPLOYEE",
"value":[
{
"Id":5000004,
"Name":"Account",
"Barcode":"EM1"
}]
}
</string>
我正在尝试避免在JSON响应周围添加字符串标签。我们怎么做到的
答案 0 :(得分:1)
我希望API可以返回JSON,这只是改变Chayim建议的Content-Type的问题。
但是,如果它仅返回xml,则可以执行以下操作:
$product[]=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$product[]["ID"]=$row["ID"];
$product[]["Name"]=$row["Productname"];
$product[]["Price"]=$row["Price"];
$product[]["Supply"]=$row["Supply"];
$product[]["Tags"]=$row["Tags"];
$product[]["Materials"]=$row["Materials"];
}
} else {
echo "0 results found. Please check database connection.";
}