2015-12-10 37 views
1

我有一個字符串,可以這個樣子:如何在不知道字段名稱的情況下反序列化json字符串?

[ 
    { 
     Id:{ 
     editable:false, 
     nullable:true 
     } 
    }, 
    { 
     Product:{ 
     validation:{ 
      required:true 
     } 
     } 
    }, 
    { 
     Cost:{ 
     type:"number", 
     validation:{ 
      required:true 
     } 
     } 
    } 
] 

它也可以是這樣的:

[ 
    { 
     Id:{ 
     editable:false, 
     nullable:true 
     } 
    }, 
    { 
     Car:{ 
     validation:{ 
      required:true 
     } 
     } 
    }, 
    { 
     Make:{ 
     validation:{ 
      required:true 
     } 
     } 
    } 
] 

的一點是,該字符串將始終有一個ID字段與一些預測的值,但其他字段可以被命名爲任何東西。

我有一些JavaScript,我需要這個樣子:

schema: { 
    model: { 
     id: "Id", 
     fields: { 
      Id: { editable: false, nullable: true }, 
      Product: { validation: { required: true } }, 
      Cost: { type: "number", validation: { required: true }} 
     } 
    } 
} 

...其中字段的內容需要字符串相關。

目前我有一個ajax調用,可以獲取我的代碼需要的其他數據,我也想給它我需要的字段的結果。我想,以取代JSON像這樣:

schema: { 
    model: { 
     id: "Id", 
     fields: ajaxResult.fields 
     } 
    } 
} 

的正常途徑是創建一個類(或類),而我可以反序列化JSON字符串,但在這種情況下,在JSON字符串中的字段可以完全任意。 所以我不能創建類,因爲我不知道什麼屬性將被稱爲

我該如何反序列化這個字符串,所以當我從Action中返回時,它會按我描述的方式工作?

目前我控制器操作看起來是這樣的:

public IActionResult GetJsonData(Guid id) 
{ 
    var model = new GridDataModel 
    { 
     schema = SchemaToJson(id), 
     //fields = FieldsToJson(id), 
     gridData = RowsToJson(id) 
    }; 
    return Json(model); 
} 
+0

是否使用Json.Net? – timothyclifford

+0

格式化您的JSON。你的JSON無效。 – RvdK

+0

'SchemaToJson()'和'RowsToJson()'返回什麼? – timothyclifford

回答

4

在Visual Studio 2015年,您可以使用「選擇性粘貼」功能,Visual Studio將生成的所有類(包括嵌套類等)爲您,需要自己的編碼不單行:

enter image description here

見動畫如下所示:(原GIF是從here

enter image description here

enter image description here

+0

這很酷......但似乎沒有解決我的問題中的任何問題。所有這一切都是保存輸入。打字不是我的問題。 –

相關問題