1

I'm trying to use HttpClient to POST a new Account via SalesForce RESTApi, but I'm receiving the following error:

message: "Can not deserialize SObject out of VALUE_STRING token at [line:1, column:1]". errorCode: "JSON_PARSE_ERROR".

I'm using the same json for WebRequest and HttpClient tests. With WebRequest, it works well.

Here is my code with HttpClient:

        var uri = "https://na15.salesforce.com/services/data/v27.0/sobjects/Account";

        var acc = new Account();
        acc.Name = "RestAPIHttpClient";

        var ser = new JavaScriptSerializer();
        var json = ser.Serialize(acc);

        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + binding.SessionHeaderValue.sessionId);

        var response = await client.PostAsJsonAsync(uri, json);
        var stringresponse = await response.Content.ReadAsStringAsync();
        Console.WriteLine(stringresponse); 

The account class that im serializing is just that simple:

    private class Account
    {
        public string Name { get; set; }
    }

UPDATE:

I changed the code to use PostAsync besides PostAsJsonAsync, then i added the JsonFormatter at the Content and now it is working. Would be great to know why PostAsJsonAsync doesn't work.

System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = 
    new System.Net.Http.Formatting.JsonMediaTypeFormatter(); 
System.Net.Http.HttpContent content = 
    new System.Net.Http.ObjectContent<Account>(acc, jsonFormatter);

var response = await client.PostAsync(uri, content); 
4

0 回答 0