我正在尝试为正在构建的Web API返回JSON。该API返回带有斜杠\
的JSON,这使我的其他应用程序很难使用此API。
" {\"@odata.context\":\"https://science.com/odata/$metadata#EMPLOYEE\",\"value\":[{\"Id\":5000004,\"Name\":\"Account\"}]}"
但我希望得到
这样的答复{
"@odata.context": "https://science.com/odata/$metadata#EMPLOYEE",
"value": [
{
"Id": 5000004,
"Name": "Account"
}]}
下面是我的Web API的代码
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;
}
我还在如下所示的WebAPIConfig文件中添加了内容类型
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
但是我仍然使用斜杠
答案 0 :(得分:2)
public async Task<Data> GetEmployee(string instance)
{
string responsedata = " {\"@odata.context\":\"https://science.com/odata/$metadata#EMPLOYEE\",\"value\":[{\"Id\":5000004,\"Name\":\"Account\"}]}";
return JsonConvert.DeserializeObject<Data>(responsedata);
}
public class Data
{
[JsonProperty("@odata.context")]
public string ODataContext { get; set; }
public Value[] Value { get; set; }
}
public class Value
{
public int Id { get; set; }
public string Name { get; set; }
}
以上代码返回字符串,并且您返回相同的响应。结果,它不是您期望的格式正确的JSON。
如果要返回正确的JSON,则需要先将字符串转换为JSON,然后再返回。
bokeh.charts