来自Web请求的文本框中的自定义字符串

huangapple go评论58阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月10日 16:35:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定