0

Is it possible to have a variable in StringContent?

Currently my Code looks like this (It's about \"text\": \"this is my message\"):

myRequestMessage.Content = new StringContent("{\"type\": \"message\", \"text\": \"this is my message\", \"from\": {\"id\": \"myID\", \"name\": \"myName\"}}", System.Text.Encoding.UTF8, "application/json");

But I want to have it like this (\"text\": "+myOwnString+"):

myOwnString = "this is my text";
myRequestMessage.Content = new StringContent("{\"type\": \"message\", \"text\": "+myOwnString+", \"from\": {\"id\": \"myID\", \"name\": \"myName\"}}", System.Text.Encoding.UTF8, "application/json");

My problem is when doing it like I want to have it I get a StatusCode 400, ReasonPhrase: Bad Request from var myResponse = await myClient.SendAsync(myRequestMessage);. So I assume I have to write it differently to make it work.

Does anyone know a fix?

1
  • 1
    You still need to wrap the string you provide in double-quotes for it to be valid json. So \"text\": \"" + myOwnString + "\" Commented Jul 29, 2019 at 14:42

2 Answers 2

5

This kind of operation becomes much easier, more readable and robust if you serialize an anonymous type instead of using concatenation:

var output = new {
    type = "message",
    text = "this is any message you want it to be",
    from = new {
            id = "myId",
            name = "myName"
    }
};

var outputJson = JsonConvert.SerializeObject(output);

Result:

{
  "type": "message",
  "text": "this is any message you want it to be",
  "from": {
    "id": "myId",
    "name": "myName"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

3

It seems like you are missing the quotes around the text that you concatenated.

Try this:

myRequestMessage.Content = new StringContent("{\"type\": \"message\", \"text\": \""+myOwnString+"\", \"from\": {\"id\": \"myID\", \"name\": \"myName\"}}", System.Text.Encoding.UTF8, "application/json");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.