asp.net核心中反序列化的动态对象

mmvthczy  于 2023-08-08  发布在  .NET
关注(0)|答案(1)|浏览(103)

我目前正面临着一个挑战,即反序列化从Umbraco CMS返回的包含动态字段的JSON对象。
从Umbraco返回的json对象是高度可定制的,可能有这样的例子。

  1. {
  2. "content": {
  3. "DataType": null,
  4. "header": {
  5. "title": "",
  6. "logo": null,
  7. "navigation": []
  8. },
  9. "footer": {
  10. "Name" : "this is the footer"
  11. "logo": null,
  12. "Links": 0.0,
  13. "copyRight": ""
  14. }
  15. }

字符串
或者更复杂的东西

  1. {
  2. "overview": "<h2>Content Overview</h2><p><a href=\"https://\">Text</a></p>",
  3. "isVisible": false,
  4. "description": "describe your product",
  5. "bulletItems": [
  6. "settings": null,
  7. "content":{
  8. "item": "confidential service",
  9. "contentType": {
  10. "key": "123",
  11. "id": 1111,
  12. "alias": "item",
  13. "itemType": "Element",
  14. "properties": [
  15. {
  16. "referenceCacheLevel": "Element",
  17. "propertyType": {
  18. "contentType": {
  19. "key": "3234234",
  20. "id": 1112,
  21. "alias": "bulletItem",
  22. "itemType": "Element",
  23. "compositionAliases": [],
  24. "variations": "Nothing",
  25. "propertyTypes": [],
  26. "isElement": true
  27. }
  28. }
  29. }
  30. ]
  31. }
  32. }
  33. ]
  34. }


具体地,接收到的对象可以包括或可以不包括诸如页眉、页脚、图标、链接、标题、内容等的字段。我的目标是反序列化这个对象,并将其放入一个标准结构(该结构涵盖了字段,数组和我们需要的对象)。如果它在我的类中具有该属性(同名),则将其反序列化并填充字段。如果它没有相关属性,则将其留空。从本质上讲,导入的JSON对象将作为数据源,并且所需的结果将是一个符合标准化结构的对象,其中所有必要的元素都进行了相应的过滤。
例如,下面是我定义的结构:

  1. public class MyContentClass
  2. {
  3. public Header header;
  4. public Footer footer;
  5. public string title;
  6. ...
  7. }
  8. public class Header
  9. {
  10. public string name;
  11. public int height;
  12. public List<property> properties;
  13. ...
  14. }
  15. public class Footer
  16. {
  17. public string name;
  18. public string content1;
  19. public string content2;
  20. public List<property> properties;
  21. ...
  22. }
  23. ...


任何意见/建议将不胜感激。

cxfofazt

cxfofazt1#

你可以通过using System.Text.Json来实现。
参考下面的代码片段:

  1. using System;
  2. using System.Text.Json;
  3. public class Program
  4. {
  5. public static void Main()
  6. {
  7. // Pass you json string or MyContentClass objects json string
  8. string jsonString = "{\"name\":\"John\",\"age\":30,\"Prop\":40,\"city\":\"New York\"}";
  9. // Deserialize the JSON string into a dynamic object
  10. dynamic dynamicObject = JsonSerializer.Deserialize<dynamic>(jsonString);
  11. Console.WriteLine(""+ dynamicObject.ToString());
  12. }
  13. }

字符串
参考工作样品here

展开查看全部

相关问题