简体   繁体   中英

How can I deserialize a json string without knowing the name of the fields?

I have a string that can look like this:

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

It can also look like this:

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

The point is that the string will always have an Id field with some predictable values, but additional fields can be named anything.

I have some javascript which I need to look like this:

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

... where the content of fields needs to correlate the string.

Currently I have an ajax call that get some other data my code needs and I would like to also give it the results I need for the fields. I would like to replace the json like so:

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

The normal route is to create a class (or classes) to which I can deserialize the json string, but in this case the fields in the json string can be completely arbitrary. So I cannot create classes for this since I don't know what the properties will be called .

How can I deserialize this string so when I return it from my Action it will work as I describe?

Currently my controller action looks something like this:

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

In Visual Studio 2015, you can use the "paste special" function, Visual studio will generate all classes (including nested classes etc.) for you, no single line of your own coding is needed:

在此处输入图片说明

See animations below: (original GIF is from here .)

在此处输入图片说明

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM