michael marmah
michael marmah

Reputation: 147

Create JSON using Dictionary in C#

Please I need to use dictionary to create a JSON as below.

 {
    "amount": "string",
    "currency": "string",
    "externalId": "string",
    "payer": {
            "partyIdType": "MSISDN",
            "partyId": "string"
    },
    "payerMessage": "string",
    "payeeNote": "string"
 }

The code below is what I use to achieve that but it doesnt get it exactly the way I want it. Can someone help me out, to see where I am going wrong so I can make the necessary changes. Thank you so much.

Dictionary<string, string> body = new Dictionary<string, string>
                    {
                        {"partyIdType","MSISDN"},
                        {"partyId","string"}
                    };
                    Dictionary<string, string> newbody = new Dictionary<string, string>
                    {
                        {"amount","string"},
                        {"currency","string"},
                        {"externalId","string"},
                        {"payer",DictionaryToString(body)},
                        {"payerMessage", "string"},
                        {"payeeNote","string"}
                    };
string data = JsonConvert.SerializeObject(newbody);
                    StringContent content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
                    HttpResponseMessage httpResponse = await client.PostAsync(uriRequest, content);



protected string DictionaryToString(Dictionary<string, string> dictionary)
    {
        string dictionaryString = "{";
        foreach (KeyValuePair<string, string> keyValues in dictionary)
        {
            dictionaryString += keyValues.Key + " : " + keyValues.Value + ", ";
        }
        return dictionaryString.TrimEnd(',', ' ') + "}";
    }

Upvotes: 0

Views: 991

Answers (1)

Longoon12000
Longoon12000

Reputation: 794

I do not recommend generating the JSON code yourself (like you do in DictionaryToString).

Instead you could try do declare the dictionary like so:

Dictionary<string, object> body = new Dictionary<string, object>()
{
    {"amount", "string"},
    {"currency", "string"},
    {"externalId", "string"},
    {"payer", new Dictionary<string, string>()
    {
        {"partyIdType","MSISDN"},
        {"partyId","string"}
    }},
    {"payerMessage", "string"},
    {"payeeNote", "string"}
};

string data = JsonConvert.SerializeObject(body);

If you use object for the dictionary you can put in any type you like, including other dictionaries, which will be correctly serialized.

Upvotes: 2

Related Questions