gpt4 book ai didi

c# - 使用 StringContent 访问 HttpResponseMessge 中的 JSON 对象

转载 作者:可可西里 更新时间:2023-11-01 16:40:05 26 4
gpt4 key购买 nike

我在访问使用 StringContent 生成的 HttpResponseMessage 中的 JSON 对象时遇到问题。

JSON 对象如下所示:

{
"object": "JOB",
"entry": [
{
"uuid": "1nufisnfiu3-dn3u2irb-dn3ui2fb9-nui2",
"changed_fields": [
"status"
],
"time": "2018-09-30 21:57:02"
}
],
"resource_url": "https://somewebsiteAPI.com/api_1.0/Jobs/1nufisnfiu3-dn3u2irb-dn3ui2fb9-nui2.json"
}

这是我的 Controller :

[HttpPost]
public async Task<HttpResponseMessage> Post()
{

string result = await Request.Content.ReadAsStringAsync();
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json");

return resp;
}

我的目标是获取 resource_url json 对象。

如有任何帮助,我们将不胜感激!谢谢!

最佳答案

需要让JSON字符串为对象,然后获取resource_url值。

我会使用 Json.net做到这一点。

  1. 为 Json 数据创建模型。

看起来像这样。

public class Entry
{
public string uuid { get; set; }
public List<string> changed_fields { get; set; }
public string time { get; set; }
}

public class RootObject
{
public List<Entry> entry { get; set; }
public string resource_url { get; set; }
}
  1. 使用JsonConvert.DeserializeObject 方法让JSON 字符串建模。

然后获取模型的 resource_url 属性并将其作为参数传递到 StringContent 中。

[HttpPost]
public async Task<HttpResponseMessage> Post()
{

string result = await Request.Content.ReadAsStringAsync();
var resp = new HttpResponseMessage(HttpStatusCode.OK);
var model = JsonConvert.DeserializeObject<RootObject>(result);
resp.Content = new StringContent(model.resource_url, System.Text.Encoding.UTF8, "application/json");
return resp;
}

关于c# - 使用 StringContent 访问 HttpResponseMessge 中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52582788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com