Home > Back-end >  Add double quotations in List to send API request in JSON
Add double quotations in List to send API request in JSON

Time:10-11

I want to add double quotation in list of each string item so that I can make a JSON request to send to api. var response = default(HttpResponseMessage); using var httpClient = CreateHttpClientForRequest();

        var kpis = string.Join<string>(",", (IEnumerable<string>)keyProcessInstance);
       
        using var requestMessage = new HttpRequestMessage(HttpMethod.Delete, PathfinderDeleteActiveUri)
        {             
            Content = new StringContent ($@"[""{kpis}""]", Encoding.UTF8, "application/json")            
        };

I need this type of format in kpis variable. ["string1","string2","string"]

but not able to add "" for each string in the kpis.

CodePudding user response:

You should use System.Text.Json.JsonSerializer to serialize your list to JSON.

using System.Text.Json;

...

string kpis = JsonSerializer.Serialize(keyProcessInstance);
       
using var requestMessage = new HttpRequestMessage(HttpMethod.Delete, PathfinderDeleteActiveUri)
{             
    Content = new StringContent(kpis, Encoding.UTF8, "application/json")            
};

For educational purposes only, this is what you could do to make it work with your own approach.

var kpis = string.Join<string>("\",\"", (IEnumerable<string>)keyProcessInstance);
       
using var requestMessage = new HttpRequestMessage(HttpMethod.Delete, PathfinderDeleteActiveUri)
{             
    Content = new StringContent($"[\"{kpis}\"]", Encoding.UTF8, "application/json")            
};

You have to use backslash to use quotes in a string \".

CodePudding user response:

You don't need to quote array values, the JSON serializer will do it automatically. In .NET 5 and later you can use JsonContent.Create to create a JsonContent object that serializes its payload automatically:

var jsonContent=JsonContent.Create(keyProcessInstance);
using var requestMessage = new HttpRequestMessage(HttpMethod.Delete, uri)
        {             
            Content = jsonContent           
        };
await client.SendAsync(requestMessage);

The default media type for JsonContent is application/json with CharSet utf-8

  • Related