如何在 C# 代码中为 POST 方法创建精确的 JSON 格式?
How to create exact JSON format to POST method in c# code?
Web 服务需要这种格式:
{
"Data":"{\"Name\":\"HelloWorld\",\"BirthDate\":\"2020-03-03\",\"BirthPlace\":\"Nowhere\"}"
}
我需要上述格式才能 post 到网络服务,但我下面的代码不符合格式。请帮忙。我一直在使用下面的代码 post
var Data = JsonConvert.SerializeObject(new
{
Data = new
{
Name= "HelloWorld",
BirthDate = "2020-03-03",
BirthPlace= "Nowhere"
}
});
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, Data);
}
要获得所需的格式,请执行以下操作:
string name = "HelloWorld";
string birthdate = "2020-03-03";
string birthplace= "Nowhere";
var jsonData = JsonConvert.SerializeObject(new
{
Data = $"\"Name\"=\"{name}\",\"BirthDate\"=\"{birthdate}\",\"BirthPlace\"=\"{birthplace}\""
});
查看实际效果:https://dotnetfiddle.net/UBXDtd
格式规定 Data
应包含 string
。您的代码序列化了一个具有属性的对象,结果是:
{"Data":{"Name":"HelloWorld","BirthDate":"2020-03-03","BirthPlace":"Nowhere"}}
编辑:虽然这可行,但我会推荐@xdtTransform 对此的回答。把它留在这里,以防他的解决方案由于某种原因不适用。
如果数据应该包含真实对象的字符串序列化。您可以使用字符串结果作为第二次序列化的值来简单地序列化内部对象。
using Newtonsoft.Json;
public static string WrapAndSerialize(object value){
return JsonConvert.SerializeObject(new { Data = JsonConvert.SerializeObject(value) });
}
像这样使用它:
var myObject=
new
{
Name = "HelloWorld",
BirthDate = "2020-03-03",
BirthPlace = "Nowhere",
};
var Data= WrapAndSerialize(myObject);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, Data);
}
Web 服务需要这种格式:
{
"Data":"{\"Name\":\"HelloWorld\",\"BirthDate\":\"2020-03-03\",\"BirthPlace\":\"Nowhere\"}"
}
我需要上述格式才能 post 到网络服务,但我下面的代码不符合格式。请帮忙。我一直在使用下面的代码 post
var Data = JsonConvert.SerializeObject(new
{
Data = new
{
Name= "HelloWorld",
BirthDate = "2020-03-03",
BirthPlace= "Nowhere"
}
});
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, Data);
}
要获得所需的格式,请执行以下操作:
string name = "HelloWorld";
string birthdate = "2020-03-03";
string birthplace= "Nowhere";
var jsonData = JsonConvert.SerializeObject(new
{
Data = $"\"Name\"=\"{name}\",\"BirthDate\"=\"{birthdate}\",\"BirthPlace\"=\"{birthplace}\""
});
查看实际效果:https://dotnetfiddle.net/UBXDtd
格式规定 Data
应包含 string
。您的代码序列化了一个具有属性的对象,结果是:
{"Data":{"Name":"HelloWorld","BirthDate":"2020-03-03","BirthPlace":"Nowhere"}}
编辑:虽然这可行,但我会推荐@xdtTransform 对此的回答。把它留在这里,以防他的解决方案由于某种原因不适用。
如果数据应该包含真实对象的字符串序列化。您可以使用字符串结果作为第二次序列化的值来简单地序列化内部对象。
using Newtonsoft.Json;
public static string WrapAndSerialize(object value){
return JsonConvert.SerializeObject(new { Data = JsonConvert.SerializeObject(value) });
}
像这样使用它:
var myObject=
new
{
Name = "HelloWorld",
BirthDate = "2020-03-03",
BirthPlace = "Nowhere",
};
var Data= WrapAndSerialize(myObject);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, Data);
}