Home > OS >  POST a string array with a key
POST a string array with a key

Time:06-13

I used to send to an API with a string array:

string[] metaArray = new string[1];
metaArray[0] = "userID buyer: "   CachedUserOurself.userID;
    
var postModel = new
{
    merchant_uid = merchant_uid_toreceiveMoney,
    products = products,
    metadata = parameters,
    ...
};

This is working code, but will in the future not work no longer. I received this information from our API service provider:

For example, your most recent transaction defines:

"metadata": [
    "userID buyer: 1419"
],

which leads to the following key-value pairs:

"metadata": [
        {
            "key": "0",
            "value": "userID buyer: 1419"
        }
],

"key": "0", is going to lead to errors in the near future. So he will need to change the code to make sure you are sending both a key and a value. So that the result will be

"metadata": [
        {
            "key": "userID buyer",
            "value": "1419"
        }
],

So, I thought OK, I will try this:

var parameters = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("key", "userId buyer"),
    new KeyValuePair<string, string>("value", CachedUserOurself.userID)
};

But this won't be accepted by the API.

How can I alter the array I used to send (and am still sending) so that it features a KEY?

Thank you!

CodePudding user response:

From:

var parameters = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("key", "userId buyer"),
    new KeyValuePair<string, string>("value", CachedUserOurself.userID)
};

This returns an array with two Key-Value pair items.

And if you serialize it, the JSON will be:

[
  { "Key": "key", "Value": "userId buyer" },
  { "Key": "value", "Value": /* CachedUserOurself.userID */ }
]

What you need is Dictionary<TKey, TValue> which implements IEnumerable<KeyValuePair<TKey, TValue>>.

The difference between KeyValuePair and Dictionary in general:

KeyValuePair - A single item.

Dictionary - Contains multiple KeyValuePair items.

var parameters = new List<Dictionary<string, string>>
{
    new Dictionary<string, string>
    {
        { "userId buyer", CachedUserOurself.userID }
    }
};

This results

[
  { "userId buyer": /* CachedUserOurself.userID */ }
]

For your senario,

var parameters = new List<Dictionary<string, string>>
{
    new Dictionary<string, string>
    {
        { "key", "userId buyer" },
        { "value", CachedUserOurself.userID }
    }
};

Result

[
  { "key": "userId buyer","value": /* CachedUserOurself.userID */ }
]

Sample .NET Fiddle

  •  Tags:  
  • c#
  • Related