C# 使用StringContent访问HttpResponseMessage中的JSON对象

C# 使用StringContent访问HttpResponseMessage中的JSON对象,c#,json,http,C#,Json,Http,我在访问使用StringContent生成的HttpResponseMessage中的JSON对象时遇到问题 以下是JSON对象的外观: { "object": "JOB", "entry": [ { "uuid": "1nufisnfiu3-dn3u2irb-dn3ui2fb9-nui2", "changed_fields": [ "status" ],

我在访问使用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"
}
这是我的控制器:

[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;
        }
[HttpPost]
公共异步任务Post()
{
字符串结果=wait Request.Content.ReadAsStringAsync();
var resp=新的HttpResponseMessage(HttpStatusCode.OK);
resp.Content=newstringcontent(结果,System.Text.Encoding.UTF8,“application/json”);
返回响应;
}
我的目标是获取resource_url json对象


任何帮助都将不胜感激!谢谢

您需要将
JSON
字符串作为对象,然后获取
resource\u url

我会用它来做的

  • 为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; }
    }
    

    应该真正让模型绑定器执行其预期的角色,而不是自己解析JSON

    [HttpPost]
    public async Task<IHttpActionResult> Post([FromBody]Job model) {
        if(ModelState.IsValid) {
    
            //...do something with model
    
            return Ok(model.ResourceUrl);
        }
        return BadRequest(ModelState);
    }
    

    模型绑定器将解析传入的JSON并填充定义为匹配所需数据的强类型对象模型

    有什么问题或错误消息?没有。它只是返回整个JSON对象,但我想得到的是资源的URL
    [HttpPost]
    public async Task<IHttpActionResult> Post([FromBody]Job model) {
        if(ModelState.IsValid) {
    
            //...do something with model
    
            return Ok(model.ResourceUrl);
        }
        return BadRequest(ModelState);
    }
    
    public partial class Job {
        [JsonProperty("object")]
        public string Object { get; set; }
    
        [JsonProperty("entry")]
        public Entry[] Entry { get; set; }
    
        [JsonProperty("resource_url")]
        public Uri ResourceUrl { get; set; }
    }
    
    public partial class Entry {
        [JsonProperty("uuid")]
        public string Uuid { get; set; }
    
        [JsonProperty("changed_fields")]
        public string[] ChangedFields { get; set; }
    
        [JsonProperty("time")]
        public DateTimeOffset Time { get; set; }
    }