无效的JSON原语:

时间:2013-03-07 14:56:55

标签: asp.net json web-services javascriptserializer

我是新手使用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));

1 个答案:

答案 0 :(得分:0)

异常很可能是由于服务调用导致抛出异常并且异常字符串不是有效的JSON对象,因此它无法解析响应。

检查以下内容:

  • 网络通话真的成功吗?如果失败,很可能是客户端上的异常处理不好,并且您正在尝试将异常对象响应转换为JSON对象,因此会显示您看到的错误消息。
  • 调用确实通过了服务器,并且有一个异常和/或调用导致返回给客户端的错误消息,该消息再次不是有效的JSON对象,因此您无法将其转换为一个。 / LI>