简体   繁体   中英

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));

Just use:

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

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

Also see: Encoding.UTF8.GetBytes

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM