英文:
Custom string from TextBox in webrequest
问题
以下是翻译好的部分:
原始请求体:
string body = ""{\"prompt\": \"MyText\",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";"
尝试更改为文本框中的文本:
string body = ""{\"prompt\":" +textBox1.Text+",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";"
但每次尝试更改 "MyText" 为文本框中的文本,都会收到来自服务器的错误 400。
有任何想法吗?
英文:
i am trying to send a HttpWebRequest with the following body :
string body = "{\"prompt\": \"MyText\",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";
the request works perfectly with this body, but everytime i try to change "MyText" with a text from textbox, i get an error 400 from server.
i tried this (return error 400):
string body = "{\"prompt\":" +textBox1.Text+",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";
any ideas ?
答案1
得分: 0
不建议手动构建JSON,因为在处理复杂对象/数组时,可能会由于缺少/多余的引号、大括号等而容易出现语法错误。
使用类库,如 System.Text.Json 或 Newtonsoft.Json 来进行JSON序列化更加安全和简便,相比手动构建而言。
using System.Text.Json;
var obj = new
{
prompt = textBox1.Text,
n = 2,
size = "256x256",
response_format = "b64_json"
};
string body = JsonSerializer.Serialize(obj);
using Newtonsoft.Json;
string body = JsonConvert.SerializeObject(obj);
英文:
It is not recommended to build your JSON manually as you will highly expose to syntax errors due to missing/extra quotes, braces, etc especially when dealing with complex objects/arrays.
Using the libraries such as System.Text.Json or Newtonsoft.Json for the JSON serialization. This is safer and easier compared to building it manually.
using System.Text.Json;
var obj = new
{
prompt = textBox1.Text,
n = 2,
size = "256x256",
response_format = "b64_json"
};
string body = JsonSerializer.Serialize(obj);
using Newtonsoft.Json;
string body = JsonConvert.SerializeObject(obj);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论