【问题标题】:Convert JSON response to Custom C# object将 JSON 响应转换为自定义 C# 对象
【发布时间】:2021-07-02 01:13:12
【问题描述】:

我正在调用网络服务并获得关注 Json 响应

{"handler":{"name":"abc"},"intent":{"name":"actions.intent.MAIN","params":{},"query":"Mit Google sprechen"},"scene":{"name":"actions.scene.START_CONVERSATION","slotFillingStatus":"UNSPECIFIED","slots":{},"next":{"name":"Start_Frage"}},"session":{"id":"ABwppHHVumDrliLJaLSikS6KnIlN7yYv6Z4XJCOYzEZt8Fr08RH6r0wtM2-E0v40lS2p1YosTDfpSCd5Lw","params":{},"typeOverrides":[],"languageCode":""},"user":{"locale":"de-DE","params":{},"accountLinkingStatus":"ACCOUNT_LINKING_STATUS_UNSPECIFIED","verificationStatus":"VERIFIED","packageEntitlements":[],"gaiamint":"","permissions":[],"lastSeenTime":"2021-04-01T10:06:59Z"},"home":{"params":{}},"device":{"capabilities":["SPEECH","RICH_RESPONSE","LONG_FORM_AUDIO"]}}

我使用https://json2csharp.com/ 将我的 Json 字符串转换为 C# 类

 public class Handler
    {
        public string name { get; set; }
    }

    public class Params
    {
    }

    public class Intent
    {
        public string name { get; set; }
        public Params @params { get; set; }
        public string query { get; set; }
    }

    public class Slots
    {
    }

    public class Next
    {
        public string name { get; set; }
    }

    public class Scene
    {
        public string name { get; set; }
        public string slotFillingStatus { get; set; }
        public Slots slots { get; set; }
        public Next next { get; set; }
    }

    public class Session
    {
        public string id { get; set; }
        public Params @params { get; set; }
        public List<object> typeOverrides { get; set; }
        public string languageCode { get; set; }
    }

    public class User
    {
        public string locale { get; set; }
        public Params @params { get; set; }
        public string accountLinkingStatus { get; set; }
        public string verificationStatus { get; set; }
        public List<object> packageEntitlements { get; set; }
        public string gaiamint { get; set; }
        public List<object> permissions { get; set; }
        public DateTime lastSeenTime { get; set; }
    }

    public class Home
    {
        public Params @params { get; set; }
    }

    public class Device
    {
        public List<string> capabilities { get; set; }
    }

    public class Root
    {
        public Handler handler { get; set; }
        public Intent intent { get; set; }
        public Scene scene { get; set; }
        public Session session { get; set; }
        public User user { get; set; }
        public Home home { get; set; }
        public Device device { get; set; }
    }

但是我该如何将我的 Json 响应解析为 C# 对象?然后对其进行任何更改并最终发送回响应?我是编程新手,这就是为什么一步一步的例子会很有帮助

我现在的班级是这样的。变量 body 保存 Json 响应。

public class GoogleController : ControllerBase
    {

        [HttpGet]
        public IActionResult Get()
        {
            var result = new Result();
            result.Value1 = 123;

            return Ok(result);
        }
        [HttpPost]
        public async Task<IActionResult> PostWebHook()
        {

            string body;
            using (var reader = new StreamReader(Request.Body))
            {
                body = await reader.ReadToEndAsync();

            }
            return Ok("Test123");
                
        }
    }

【问题讨论】:

  • 您不必显式反序列化请求内容。如果动作接受一个匹配 JSON 主体的对象,ASP.NET 会自动反序列化它
  • 也许浏览一些基本的 MVC 教程是个好主意。这是其工作原理的基础。

标签: c# asp.net json json.net deserialization


【解决方案1】:

使用FromBody属性反序列化body

    [HttpPost]
    public async Task<IActionResult> PostWebHook([FromBody] Root root)
    {
        // root is deserialized body
        // modify root
        ...
        return Ok(root);
    }

【讨论】:

    【解决方案2】:

    https://json2csharp.com/ 在第一行添加一个命令,例如:

    Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    

    此行用于反序列化文本。

    你的应该是这样的:

    var myDeserializedClass = JsonConvert.DeserializeObject<Root>(body);
    

    【讨论】:

    • 这是非常手动的并且依赖于正在使用的 JSON.Net。相反,只需让框架为您执行此操作,如另一个答案所示。
    • @DavidG 你是对的,arther 的答案更好
    猜你喜欢
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多