Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to POST 2 dimensional objects using System.Net.Http

Hello stackoverflow users,

I am currently trying to POST some data to a webhook in my C# project. But I ran into some problems trying to push something more than 1 dimensional objects in a Dictionary.

I am using the C# given methods:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 private async void SendPOST(Dictionary<string, string> val)
    {
        var content = new FormUrlEncodedContent(val);
        var restponse = await client.PostAsync("https://myWebServer.com/fakeaddress", content);            
        var responseString = await restponse.Content.ReadAsStringAsync();

        Print("Respons: " + responseString);
    }

This works fine for default key-value pairs in the dictionary when the requirements look like this:

"customer": "peter",
"bank": "global bank",
"value": "2000.00",
"currency": "USD",
"location": "Berlin"

But the webhook requires something like this:

"customer": "peter",
"bank": "global bank",
"accountData": {
    "value": 2000.00,
    "currency": "USD"
    },
"location": "Berlin"

How can I POST the required fields?
I did try to simply cheat my way around using a stringbuilder and create the JSON myself, but the PostAsync only accepts content objects and the FormUrlEncodedContent only simple key – value pairs. Am I missing something here?

edit1: format

>Solution :

You should use a custom object instead of a Dictionary<string, string>

public class AccountData{
  public double Value {get; set;}
  public string Currency {get; set;}
}

public class Account {
  public string Customer {get; set;}
  public string Bank {get; set;}
  public AccountData AccountData {get; set;}
  public string Location {get; set;}
}

Then you can Serialize the object to json and that’s it.

Edit:
Then change

var content = new FormUrlEncodedContent(val);

to

var content = new StringContent(<yourserializedjson>, Encoding.UTF8, "application/json");

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading