Roadside Romeozz
Roadside Romeozz

Reputation: 83

convert string to ByteArray C#

I am trying to pass the below string as parameter in Web API POST

devKey=test&sessionId=!bUUfUjXzPX&data={"nested": true,"start" : 2,"max" : 999}

But I am unable to convert it to Byte array, it throws the following error:

Throwing 'Input string was not in a correct format.' error due to {}

Can you please suggest a way to convert or to POST(HttpWebRequest) in any other way.

I tried the code below, and I used a similar method before, but those strings didn't consists of {} and worked fine.

string strNewValue = "devKey=" + _devKey + "&userName=" + _uName + "&password=" + _pwd;
byte[] byteArray = Encoding.UTF8.GetBytes(string.Format(strNewValue));

Upvotes: 0

Views: 2450

Answers (2)

Stefan
Stefan

Reputation: 17678

Just use:

byte[] byteArray = Encoding.UTF8.GetBytes(strNewValue);

a string.Format tries to format your string within the {} blocks.

Also see: Encoding.UTF8.GetBytes

Upvotes: 2

E. Verdi
E. Verdi

Reputation: 320

Hopefully Stefan's answer will help you. But in my opinion, you need to change the way you send the data to the web API. You are already using an POST request. So create an object you can sent as a body to the web API.

First create an object in C#. For "data={"nested": true,"start" : 2,"max" : 999}" that will be:

public class NameOfClass
{
    public bool Nested { get; set; }   
    public int Start { get; set; }
    public int Max { get; set; }
}

For devKey=test&sessionId=!bUUfUjXzPX&data={"nested": true,"start" : 2,"max" : 999} I would create:

public class NameOfBiggerClass
{
    public string DevKey { get; set; }   
    public string SessionId { get; set; }
    public NameOfClass Data { get; set; }
}

You can send the object as Json by adding a parameter in your request and place the object as json is this parameter.

public void SendObjectInPostRequest(string source, NameOfBiggerClass requestBody)
{
    var request = new RestRequest(source, Method.POST);
        request.AddParameter(
            "application/json; charset=utf-8",
            JsonConvert.SerializeObject(requestBody),
            ParameterType.RequestBody);
        _client.Execute(request);
}

Upvotes: 2

Related Questions