locked
Post to Web API with JSON returns syntax error RRS feed

  • Question

  • User1567530616 posted

    I am attempting to update (post) product information via a web API. I tested this successfully in Insomnia to verify that the two headers that are required and the data is correct. The two headers I need are:
    "X-Miva-API-Authorization", "MIVA xxxxxxxxxxxxxxxxxxxxxx" (Note: The xxxx is where I put in my token)
    "Content-Type", "application/json"

    The data for the products is shown below in the code.

    Most of the time when I run this I am getting this error: line #1 - Syntax error:Expected { or [

    I have looked at lots of examples and tried various options. You can see some of the options in the code that has been commented out. They pretty much all give me the same error.

    If anyone has any ideas what I am doing wrong, I would sure appreciate your input.

    Thanks. God bless you!

    Bob


    using (HttpClient client = new HttpClient())
    {

    var myJson = new Dictionary<string,string>
    {
    {"Store_Code", "SL"},
    {"Function", "Product_Insert"},
    {"Product_Code", "Z996"},
    {"Product_Name", "Test"},
    {"Product_Price", "5.00"},
    {"Product_Weight", "0.26"}
    };

    string strMyJson = JsonConvert.SerializeObject(myJson);

    client.DefaultRequestHeaders.Add("X-Miva-API-Authorization", "MIVA xxxxxxxxxxxxxxxxxxxxxx");
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    //client.DefaultRequestHeaders.Add("Content-Type", "application/json"); ** If I include this i get a "misused header name" error
    //client.DefaultRequestHeaders.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.PostAsJsonAsync("https://store.joncourson.com/mm5/json.mvc", strMyJson);
    //var response = await client.PostAsJsonAsync("https://store.joncourson.com/mm5/json.mvc", strMyJson);
    //var response = await client.PostAsJsonAsync("https://store.joncourson.com/mm5/json.mvc", "{\"Store_Code\": \"SL\"}");
    //var response = await client.PostAsync("https://store.joncourson.com/mm5/json.mvc", "{\"Store_Code\": \"SL\"}", new JsonMediaTypeFormatter());
    //var response = await client.PostAsync("https://store.joncourson.com/mm5/json.mvc", strMyJson, new JsonMediaTypeFormatter());

    string resultContent = await response.Content.ReadAsStringAsync();
    MessageBox.Show(resultContent);

    }

    Friday, May 17, 2019 5:09 PM

All replies

  • User1120430333 posted

    I can't say that I would use a dictionary, but rather,  I would just use a DTO that is known by the client and WebAPI, which is using Encapsulation. 

    https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)

     Encapsulation is one of the fundamentals of OOP (object-oriented programming). It refers to the bundling of data with the methods that operate on that data.[5] Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. Publicly accessible methods are generally provided in the class (so-called getters and setters) to access the values, and other client classes call these methods to retrieve and modify the values within the object. 

    https://en.wikipedia.org/wiki/Data_transfer_object

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

    [HttpPost]
    [Route("CreateProject")]
    public void Post_CreateProject(DtoProject dto)
    {
       _daoProject.CreateProject(dto);
    }
                    public void CreateProjectApi(DtoProject dto) 
    { using (var client = new HttpClient { BaseAddress = new Uri("http://progmgmntcore2api.com") }) { string serailizeddto = JsonConvert.SerializeObject(dto); var inputMessage = new HttpRequestMessage { Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json") }; inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = client.PostAsync("api/project/CreateProject", inputMessage.Content).Result; if (!message.IsSuccessStatusCode) throw new Exception(message.ToString()); } }
    using System;
    
    namespace Entities
    {
        public class DtoProject
        {
            public int ProjectId { get; set; }
            public string ClientName { get; set; }
            public string ProjectName { get; set; }
            public string Technology { get; set; }
            public string ProjectType { get; set; }
            public string UserId { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal Cost { get; set; }
        }
    }
    

    Friday, May 17, 2019 9:02 PM
  • User61956409 posted

    Hi searchlightadmin,

    Based on the code that you shared, we can find you are using HttpClientExtensions.PostAsJsonAsync<T> Method to make a Post request and you are supplying a string, it would try to deserialize to an object while code is executing, which causes the issue.

    To achieve the requirement, you can define and post product object (rather than a json string) with your request, like below.

    var mydata = new Product() { Store_Code= "SL", Function= "Product_Insert", Product_Code= "Z996", Product_Name= "Test", Product_Price = "5.00", Product_Weight= "0.26" };
    
    //code logic here
    
    var response = await client.PostAsJsonAsync("your_endpoint_here", mydata);

    Definition of Product:

    class Product
    {
        public Product()
        {
        }
    
        public string Store_Code { get; set; }
        public string Function { get; set; }
        //...
        //other fields
    }

    With Regards,

    Fei Han

    Monday, May 20, 2019 3:31 AM
  • User1567530616 posted

    Fei,

    Thank you so much for your response. Unfortunately, I am getting an error when I run the code: Invalid Request Content Type

    Any ideas on why I am getting this error?

    Below is the revised code.

    Thanks.

    Bob Thornley

    using (HttpClient client = new HttpClient())
    {
    var mydata = new Product() {
    Store_Code = "SL",
    Function = "Product_Insert",
    Product_Code = "Z996",
    Product_Name = "Test",
    Product_Price = "5.00",
    Product_Weight = "0.26"
    };

    client.DefaultRequestHeaders.Add("X-Miva-API-Authorization", "MIVA xxxxxxxxxxxx");
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.PostAsJsonAsync("https://store.joncourson.com/mm5/json.mvc", mydata);

    string resultContent = await response.Content.ReadAsStringAsync();
    MessageBox.Show(resultContent);

    }

    (and I added the Product class)

    Tuesday, May 21, 2019 6:12 PM
  • User1120430333 posted

    (and I added the Product class)

    Where did you serialize the object into Json from the client, since that is the default context- type a Json based WebAPI expects?

    Tuesday, May 21, 2019 10:45 PM
  • User1567530616 posted

    I forgot to add that line of code (to serialize the object) back into my new test code.

    I have now added that and i'm back to the original error: line #1 - Syntax error:Expected { or [

    Here is the current code:

    var mydata = new Product() {
    Store_Code = "SL",
    Function = "Product_Insert",
    Product_Code = "Z996",
    Product_Name = "Test",
    Product_Price = "5.00",
    Product_Weight = "0.26"
    };

    string strmydata = JsonConvert.SerializeObject(mydata);

    client.DefaultRequestHeaders.Add("X-Miva-API-Authorization", "MIVA xxxxxxxxxxxxxxx");
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.PostAsJsonAsync("https://store.joncourson.com/mm5/json.mvc", strmydata);

    string resultContent = await response.Content.ReadAsStringAsync();
    MessageBox.Show(resultContent);

    class Product
    {
    public Product()
    {
    }

    public string Store_Code { get; set; }
    public string Function { get; set; }
    public string Product_Code { get; set; }
    public string Product_Name { get; set; }
    public string Product_Price { get; set; }
    public string Product_Weight { get; set; }
    }

    Wednesday, May 22, 2019 12:32 AM
  • User1120430333 posted

    string strmydata = JsonConvert.SerializeObject(mydata);

    post the content of strmydata and use {;} to format code or data, which is an icon on the toolbar

    One other thing, are you even close to matching the code I posted in serializing the  .NET object to Json, becuase my code has more to it than just the code you have above?

    Wednesday, May 22, 2019 6:13 AM