【问题标题】:How to create custom JSON with WebMatrix's Json Helper?如何使用 WebMatrix 的 Json Helper 创建自定义 JSON?
【发布时间】:2012-12-14 17:28:09
【问题描述】:

到目前为止,我已经看到了 WebMatrix 的 Json Helper 的基本用法,例如在 here 和 here 中。这些示例展示了如何将 List 直接转换为简单的 JSON,但我想知道如何创建更自定义的 JSON。

我的意思是,这些示例将 List 编码为如下所示的 JSON:

[
  {obj1_property1 : obj1_value1,...}, 
  {obj2_property1 : obj2_value1,...}, 
  ...., 
  {objN_property1 : objN_value1,...}
]

我想要创建的内容如下:

{
  customProperty1 : customPropertyValue1, 
  customProperty2 : customPropertyValue2, 
  entries : [
    {obj1_property1 : obj1_value1,...}, 
    {obj2_property1 : obj2_value1,...}, 
    ...., 
    {objN_property1 : objN_value1,...}
  ]
}

如何使用 Json Helper 创建这种 JSON?还是我需要使用其他东西?感谢您的帮助。

【问题讨论】:

    标签: .net json code-first webmatrix helpers


    【解决方案1】:

    如果您没有找到更好的方法,那么很容易设置一个独立的剃须刀页面 .cshtml,如下所示。然后 URL 直接返回一个 JSON 字符串。

    @{
        // write whatever C# code is necessary to get object data
        ...
    }
    
    {
        "customProperty1":"@cp1",
        "customProperty2":"@cp2",
        ...
    }    
    

    【讨论】:

    • 但是如果我有一个包含多个对象的 List,我应该如何显示它们?
    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多