我是新手使用API并使用asp.net从他们那里获得响应我正在我的asp.net Web应用程序中调用API,如下所示:
public ActionResult MakeCall() {
CallTRunkAPIResponse response = GET("https://apibetaus.calltrunk.com/api/v2/GetAccountSummarySimple?access_token=mytokenkeyhere");
return Content("Make a call");
}
我创建了一个获取响应的方法,将响应传输到json格式,然后使用javascript序列化器转换为我的对象类型,如下所示:
public CallTRunkAPIResponse GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Headers.Add("X-Client:" + "header info from api here");
request.Headers.Add("X-Authenticator-Session:" + "session key from api here");
request.Method = "GET";
request.ContentType = "application/json";
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
//return reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
CallTRunkAPIResponse myojb = (CallTRunkAPIResponse)js.Deserialize(objText, typeof(CallTRunkAPIResponse));
return myojb;
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
}
我的对象是这样的(不知道下面的响应我应该在这个响应类中有哪些属性:
public class CallTRunkAPIResponse {
public string Status { get; set; }
public string Content { get; set; }
public string Region { get; set; }
}
响应应该是这样但我得到错误:
{
"Status":"OK",
"Content":{
"Region":"beta.us",
"CurrencyCode":"USD",
"CurrencySymbol":"$",
"Languages":["en"],
"Version":{
"Api":{
"DisplayVersion":"2.0",
"Version":3},
"Client":{
"ReportedVersion":0,
"NewestVersion":2,
"MinVersion":2}
}
}
}
但是我收到了这个错误:
System.ArgumentException: Invalid JSON primitive: .
在:
CallTRunkAPIResponse myojb = (CallTRunkAPIResponse)js.Deserialize(objText, typeof(CallTRunkAPIResponse));
答案 0 :(得分:0)
异常很可能是由于服务调用导致抛出异常并且异常字符串不是有效的JSON对象,因此它无法解析响应。
检查以下内容: