如何在C#的RestRequest中为JSON的message属性赋值变量
message with a Variable in C# Hey there! I see you want to swap out that hardcoded message value in your JSON payload for a variable—smart move, this makes your code way more reusable and easier to maintain. Let's walk through a few reliable approaches, from quick fixes to the most robust solution:
1. String Interpolation (C# 6+)
This is a straightforward way if you want to stick with string-based JSON. Just define your message variable, then use interpolated strings (with a verbatim @ string to avoid escaping newlines, and double curly braces {{}} to preserve the JSON braces):
// Define your message variable first var messageValue = "c3BlZWQgZXhjZWVkZWQh"; // Or any dynamic value you need var client = new RestClient("172.16.255.254:2016/settings"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); // Use interpolated verbatim string to insert the variable var jsonPayload = $@"{{ ""_id"": ""98e8d3cd47fad6ce8e3f7b8d42cb4d9b"", ""_type"": ""SetRealtimeMessage"", ""message"": ""{messageValue}"", ""width"":240, ""fontBackground"":0, ""fontColor"": 0xFFFFBF00, ""fontSize"": 24, ""lineSpace"": 0, ""left"": 0, ""windowBackground"": 0, ""verticalPos"": 0, ""horizontalPos"": 0, ""showType"": 0, ""speed"": 20, ""moveCount"": 1, ""residenceTime"": -1 }}"; request.AddParameter("application/json", jsonPayload, ParameterType.RequestBody); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content);
2. String.Format (Older C# Versions)
If you're working with a pre-C# 6 project, String.Format works similarly—you'll just use placeholders like {0} instead of interpolated variables:
var messageValue = "c3BlZWQgZXhjZWVkZWQh"; var jsonPayload = string.Format(@"{{ ""_id"": ""98e8d3cd47fad6ce8e3f7b8d42cb4d9b"", ""_type"": ""SetRealtimeMessage"", ""message"": ""{0}"", ""width"":240, ""fontBackground"":0, ""fontColor"": 0xFFFFBF00, ""fontSize"": 24, ""lineSpace"": 0, ""left"": 0, ""windowBackground"": 0, ""verticalPos"": 0, ""horizontalPos"": 0, ""showType"": 0, ""speed"": 20, ""moveCount"": 1, ""residenceTime"": -1 }}", messageValue);
3. Use a Strongly-Typed Class + JSON Serialization (Recommended)
This is the best long-term approach—no more messy string escaping or syntax errors in your JSON. You'll create a class that matches your JSON structure, populate its properties (including your dynamic message), then serialize it to JSON.
First, define the class:
public class SetRealtimeMessageRequest { public string _id { get; set; } public string _type { get; set; } public string message { get; set; } public int width { get; set; } public int fontBackground { get; set; } public int fontColor { get; set; } public int fontSize { get; set; } public int lineSpace { get; set; } public int left { get; set; } public int windowBackground { get; set; } public int verticalPos { get; set; } public int horizontalPos { get; set; } public int showType { get; set; } public int speed { get; set; } public int moveCount { get; set; } public int residenceTime { get; set; } }
Then use it in your code (using Newtonsoft.Json, which is common with RestSharp; or System.Text.Json if you prefer):
var messageValue = "c3BlZWQgZXhjZWVkZWQh"; var client = new RestClient("172.16.255.254:2016/settings"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); // Populate the request object var requestPayload = new SetRealtimeMessageRequest { _id = "98e8d3cd47fad6ce8e3f7b8d42cb4d9b", _type = "SetRealtimeMessage", message = messageValue, width = 240, fontBackground = 0, fontColor = 0xFFFFBF00, fontSize = 24, lineSpace = 0, left = 0, windowBackground = 0, verticalPos = 0, horizontalPos = 0, showType = 0, speed = 20, moveCount = 1, residenceTime = -1 }; // Serialize to JSON var jsonPayload = JsonConvert.SerializeObject(requestPayload, Formatting.Indented); request.AddParameter("application/json", jsonPayload, ParameterType.RequestBody); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content);
Why this is better:
- No JSON syntax errors: The serializer handles all escaping and formatting for you.
- Type safety: You'll get compile-time errors if you misspell a property name or use the wrong data type.
- Easier to maintain: Updating the payload structure just means modifying the class, not hunting through a string.
内容的提问来源于stack exchange,提问作者Jaswandi Lande

