【问题标题】:Alternatives to Dynamic JsonParsing动态 JsonParsing 的替代方案
【发布时间】:2016-06-15 18:47:44
【问题描述】:

我正在使用 aws lambda 的 api 请求模板来创建和调用 post 方法。我必须从我的代码中发送一个帖子正文,它应该是 json 序列化的。

这是我现在正在做的一种方式:

**dynamic pObj = new JObject();
pObj.Url = DownloadURL;
pObj.Name = IName;
pObj.ID = I.ID;**

 Custom redirect = new Custom()
 {
     url = new Uri(lambdaEndpoint),
     **Body = pObj.ToString(),**
     Method = "POST",
     Available = true
 };

但我阅读了article,其中谈到了使用动态关键字的性能问题。

是否有另一种性能更好的替代方法?任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 如果“Body”正在接受痛苦文本...您始终可以手动构建 json 字符串,而无需创建动态对象来反序列化它
  • 你能分享你的json吗?
  • @aloisdg 我的 json 非常简单:就在这里。 { "Url":"xyz.com", "Name":"abc", "ID":"123" }

标签: c# dynamic aws-lambda jsonserializer


【解决方案1】:

使用dynamic 的替代方法是直接反序列化。既然你知道你的对象,它应该符合预期。

Demo

    using System;
    using Newtonsoft.Json;


    public class Program
    {
        // create you class. You can generate it with http://json2csharp.com/ or use Visual Studio (edit>past special)
        public class Custom
        {
            public string Url { get; set; }
            public string Name { get; set; }
            public string Id { get; set; }
        }

        public void Main()
        {
            string json = "{ \"Url\":\"xyz.com\", \"Name\":\"abc\", \"ID\":\"123\" }";
            // the magic code is here! Go to http://www.newtonsoft.com/json for more information
            Custom custom = JsonConvert.DeserializeObject<Custom>(json);

            // custom is fill with your json!
            Console.WriteLine(custom.Name);
        }
    }

输出:

abc

【讨论】:

    猜你喜欢
    • 2017-06-28
    • 1970-01-01
    • 2023-03-24
    • 2012-03-14
    • 2014-02-24
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多