Home > OS >  C# - Remove @ char from property reserve name before sending post request using await client.PostAsJ
C# - Remove @ char from property reserve name before sending post request using await client.PostAsJ

Time:03-24

I am consuming an API endpoint on which I don't have any control.

API expects JSON post in this format

{
  "type": "test" 
}

I have a model

public class MyClass 
{

    public string type { get; set; }
}

Which I populate like this.

  MyClass myclass = new MyClass()
            {
                type = "something",
  }

because "type" is a reserve world in C# it changes the name to @type = "something",

When I call it using

HttpResponseMessage response = await client.PostAsJsonAsync("/abcd", myclass);

It sends the JSON

            {
                @type = "something",
  }

because API expect "type" and it gets @type, it throws an error bad request.

What is the best way I can pass "type" without @ sign in it?

CodePudding user response:

Thats really strange, I have never heard of that 'reserved word replaced by @' thing in any C# engine before. Are you sure thats the reason?

Also, in my test, it deserializes correctly.

https://dotnetfiddle.net/mMnKlr

Could you try to post it differently, like:

    var x = new MyClass(){type = "a"};
    var text = System.Text.Json.JsonSerializer.Serialize(x);

    var content = new FormUrlEncodedContent(new[]
      {
        new KeyValuePair<string, string>("", text)
      }
    );

    var result = await client.PostAsync("/abcde", content);

and look at the text before sending.

If text is okay, and you still send that strange json, its either the HttpClient doing strange things, or your proxy replacing strange things.

Also, its strange that you use a relative Url in PostAsJsonAsync, but I assume you just wrote "/abcde" as example.

CodePudding user response:

1 :

Add JsonProperty to @type

public class MyClass 
{
    [JsonProperty("type")]
    public string @type{ get; set; }
}

And serialize it using Newtonsoft.Json

MyClass myclass = new MyClass()
{
     @type = "something",
}
var value = JsonConvert.SerializeObject(myclass , Formatting.Indented);
HttpResponseMessage response = await client.PostAsJsonAsync("/abcd", value);

2 :

Add JsonPropertyName to @type

public class MyClass 
{
    [JsonPropertyName("type")]
    public string @type{ get; set; }
}

And serialize it using System.Text.Json.JsonSerializer

MyClass myclass = new MyClass()
{
     @type = "something",
}
var value = System.Text.Json.JsonSerializer.Serialize(myclass);
HttpResponseMessage response = await client.PostAsJsonAsync("/abcd", value);
  • Related