你可以试试这个:
//Yours entity.
MyEntity myEntity;
HttpResponseMessage response;
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://yourApiAdress.com");
//Yours string value.
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("MyStringContent", "someString")
});
//Sending http post request.
response = await httpClient.PostAsync($"rest/of/apiadress/", content);
}
//Here you save your response to Entity:
var contentStream = await response.Content.ReadAsStreamAsync();
//Options to mach yours naming styles.
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance
};
//Here you go. Yours response as an entity:
myEntity = await JsonSerializer.DeserializeAsync<MyEntity>(contentStream, options);
蛇 case 命名策略:
using Newtonsoft.Json.Serialization; //For SnakeCaseNamingPolicy.
public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
private readonly SnakeCaseNamingStrategy _newtonsoftSnakeCaseNamingStrategy
= new SnakeCaseNamingStrategy();
public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();
public override string ConvertName(string name)
{
return _newtonsoftSnakeCaseNamingStrategy.GetPropertyName(name, false);
}
}
如果您的另一个API JSON响应如下所示:
{
"some_object" : "someValue",
}
那么您的实体应该看起来像:
public class MyEntity
{
public object SomeObject { get; set;}
}