【问题标题】:c#: deserializing a JSON containing a local propertyc#:反序列化包含本地属性的 JSON
【发布时间】:2020-09-14 12:22:52
【问题描述】:

我反序列化一个如下所示的 JSON:

{
    "id": "FF478946-8536-4295-AC58-F6C3D2B4E5CC",
    "title": "This is a Title with an escaped variable: {VariableName}",
    "weight": 50
}

使用 Newtonsoft 到相应的对象:

public class Event
{
    public string Id { get; set; }
    public string Title { get; set; }
    public int Weight { get; set; }
}

然后我想打印字符串 Title,它引用代码中的本地字符串属性。 VariableName

private string VariableName { get; set; }
private Event CurrentEvent { get; set; }

public void OnNextEventClicked()
{
   Log(CurrentEvent.Title);
}

我试图用不同的方法来转义变量,如反斜杠 ("title": "This is a Title with an escaped variable: \"VariableName\"") 或上面代码中的大括号,但我失败了... C# 总是将转义的变量视为标题的正常部分 字符串。

最好的方法是什么?谢谢!

【问题讨论】:

  • 为什么不将variableName 作为参数添加到您的 JSON 中?
  • 因为还有很多反序列化的Event 实例根本不需要引用本地属性。其他需要引用完全不同的本地属性。 (所以想象一下,你不仅有VariableName,还有VariableName1VariableName2 等等。)所以为可能的组合编写自己的类变得太大了……
  • 然后,使用您重复的问题的答案:stackoverflow.com/questions/39874172/…
  • 是的,这就是工作!谢谢!

标签: c# json json.net


【解决方案1】:

也许您需要的只是一个string.Replace()。您可以使用nameof() 在字符串中获取变量名的名称:

private string VariableName { get; set; }
private Event CurrentEvent { get; set; }

public void OnNextEventClicked()
{
    var message = (CurrentEvent.Title).Replace(
        "{" + nameof(VariableName) + "}", 
        VariableName
    );
    Log(message);
}

【讨论】:

    【解决方案2】:

    就像 @Roman Ryzhiy 在 cmets 中指出的那样,dynamic string interpolation 已经存在很好的威胁。

    对我来说完美的解决方案是基于this answer

    使用 System.Linq.Dynamic 的辅助方法

    public string ReplaceMacro(string value, object @object)
    {
        return Regex.Replace(value, @"{(.+?)}", 
        match => {
            var p = Expression.Parameter(@object.GetType(), @object.GetType().Name);                
            var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, match.Groups[1].Value);
            return (e.Compile().DynamicInvoke(@object) ?? "").ToString();
        });
    }
    

    我的完整解决方案:

    JSON:

    {
    "id": "FF478946-8536-4295-AC58-F6C3D2B4E5CC",
    "title": "This is a Title with an escaped variable: {TitleReplacement.VariableName}",
    "weight": 50
    }
    

    C#:

    数据类:

    public class Event
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public int Weight { get; set; }
    }
    

    带有替换字符串的类:

    public class TitleReplacement
    {
        public string VariableName { get; set; }
    }
    

    这样称呼:

    private Event CurrentEvent { get; set; }
    private TitleReplacement Replacement { get; set; }
    
    public void OnNextEventClicked()
    {
        Log(ReplaceMacro(CurrentEvent.Title, Replacement);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 2010-10-31
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多