Home > Mobile >  How to POST 2 dimensional objects using System.Net.Http
How to POST 2 dimensional objects using System.Net.Http

Time:04-20

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:

 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

CodePudding user response:

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.

Then change

var content = new FormUrlEncodedContent(val);

to

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

  • Related