【问题标题】:JSON assign JObject property name with string variableJSON 使用字符串变量分配 JObject 属性名称
【发布时间】:2017-04-18 16:52:42
【问题描述】:

我的 JSON 对象中的属性名称需要通过字符串分配,如何使用 JObject 执行此操作?或者我应该只从字符串中提取 JObject.parse 吗?我知道 .Net Json 文档,但是,它非常基础,没有显示如下示例。

这是我现在拥有的:

return JObject.FromObject(new { 
attachment = new { 
    type = "template",
    payload = new {
        template_type = "button",
        text = Title,
        buttons = new {
            type = type,
            Variable1 = Value,
            Variable2 = Payload
        }
    }               
}
});

另外,如果我像下面这样使用 string.parse 方式,这是格式化字符串的最佳方式吗?

JObject.Parse(@"{
    attachment : { 
        type : 'template',
        payload : {
            template_type : 'button',
            text : '"+Title+@"',
                buttons : [{
                  type : '"+Type+@"',
                  "+Variable1+" : '"+Value+@"',
                  "+Variable2+" : '"+Payload+@"'
                }]      
        }
    }
}"

【问题讨论】:

  • 我不完全确定我是否遵循了这个问题。在第一个示例中,用作属性名称的字符串是什么?
  • 使用Dictionary<string,object>
  • @dbc 所以在第二个示例中可以很好地分配变量 1 和变量 2,因为它是一个简单的字符串。但是,在第一个示例中,我无法为属性名称 variable1 和 variable2 分配实际变量,当我运行代码时,它使用名称 Variable1 而不是其值。
  • @james:你们两个 sn-ps 不一致。第一个,buttons 是一个对象,第二个它是一个数组(其中包含一个对象)。是哪个?
  • 第二个是正确的,抱歉我不知道如何正确地做第一个

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


【解决方案1】:

您可以使用外部匿名类型对象中包含的Creating JSON: Creating JSON with LINQ 中的模式手动构造内部JObject,然后将整个匿名对象序列化为JSON:

var obj = JObject.FromObject(new
{
    attachment = new
    {
        type = "template",
        payload = new
        {
            template_type = "button",
            text = Title,
            buttons = new JArray( new JObject(
                new JProperty("type", Type),
                new JProperty(Variable1, Value),
                new JProperty(Variable2, Payload)))
        }
    }
});

示例fiddle

【讨论】:

    【解决方案2】:

    buttons 使用Dictionary<string,object>,例如:

    var obj = JObject.FromObject(new
    {
        attachment = new
        {
            type = "template", 
            payload = new
            {
                template_type = "button", 
                text = Title, 
                buttons = new object[] 
                { 
                    new Dictionary<string,object>() 
                    {
                        { "type", "type" },
                        { Variable1, Value },
                        { Variable2, Payload }
                    }
                }
            }
        }
    });
    

    【讨论】:

    • 谢谢,但我知道这会比其他答案中的 JArray 和 JObjects 表现更好吗?
    • @james:这比到处都有一大堆new JProperty 要简单得多。
    • 顺便说一句,您的答案平均执行时间为 28 毫秒,而另一个答案在我的 mac 服务器上执行的平均时间为 10 毫秒。 :)
    猜你喜欢
    • 2015-11-06
    • 2013-09-16
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多