由于字符无效,无法从Graph API反序列化错误响应

时间:2016-07-25 02:01:26

标签: office365 office365api microsoft-graph

我从Graph API获得的错误响应如下。

{   "错误":{     "代码":" ErrorItemNotFound",     " message":"在商店中找不到指定的对象。",     " innerError":{       " request-id":" c2b32b83-5ccf-4385-bee1-33afcc31deb0",       " date":" 2016-07-25T00:25:16"     }   } }

当我尝试将响应反序列化为我自己的错误对象时,我收到错误

  

解析值时遇到意外的字符:。路径'',行   0,位置0。

复制上面的JSON并尝试使用此工具进行验证 https://jsonformatter.curiousconcept.com/

其他人有同样的问题吗?

更新

很抱歉迟到的回复家伙。以下是我正在使用的确切代码。我刚刚再次测试了这个,我得到了同样的错误。

Enpoint网址:https://graph.microsoft.com/v1.0/users/MY_USER@EMAIL/events/

// New rest client with the destination URL.
        var client = new RestClient(url);

        // Type of request
        var request = new RestRequest(requestType);

        // Headers
        request.AddHeader("Authorization", "Bearer " + accessToken);
        request.AddHeader("Content-Type", "application/json");


        // Content serialized in a json format  
        if (requestType == Method.POST || requestType == Method.PATCH || requestType == Method.PUT)
        {
            var jsonBody = JsonConvert.SerializeObject(requestContent);
            request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);
        }


        var response = await client.ExecuteTaskAsync(request);

请求正文

{"Id":null,"Subject":"Maths","UserEmailAddress":"sample@sample.onmicrosoft.com","Start":{"DateTime":"2016-09-1T10:11:56","TimeZone":"Pacific/Auckland"},"End":{"DateTime":"2016-09-1T11:11:56","TimeZone":"Pacific/Auckland"},"Location":null,"Body":null,"ReminderMinutesBeforeStart":60,"IsReminderOn":true}

1 个答案:

答案 0 :(得分:2)

您发布的JSON文本实际上包含3字节的UTF-8 BOM(0xEF 0xBB 0xBF)。这将导致大多数JSON解析器失败。

解决问题的一个简单方法是检测BOM并在解析之前将其删除。

假设使用JavaScript,下面的内容将解决您的问题。

<!-- language: lang-js -->
// Reading the string into JavaScript will convert the BOM from the 3-byte
// version to the 2-byte version (0xFEFF).
json = json.replace(/^\uFEFF/, '');

-

更多

首先要弄清楚为什么甚至会将这些错误附加到产生的错误上会更有价值。您如何处理导致此错误的请求?如果这是来自网页,那么页面编码是什么?您是否正在设置可能与所需编码相关的任何其他HTTP请求标头?