在StringContent中使用变量

时间:2019-07-29 14:40:23

标签: c# json string

是否可以在StringContent中使用变量?

当前我的代码如下(大约是\"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");

但是我想要这样(\"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");

我的问题是,在执行该操作时,我想从StatusCode 400, ReasonPhrase: Bad Request获得一个var myResponse = await myClient.SendAsync(myRequestMessage);。所以我认为我必须写不同的文字才能使它工作。

有人知道解决办法吗?

2 个答案:

答案 0 :(得分:5)

如果您将匿名类型序列化而不是使用串联,则这种操作将变得更加容易,可读性和鲁棒性:

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

结果:

{
  "type": "message",
  "text": "this is any message you want it to be",
  "from": {
    "id": "myId",
    "name": "myName"
  }
}

答案 1 :(得分:2)

似乎您丢失了所连接文本周围的引号。

尝试一下:

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