Deserialize json based on fields in .Net (C#)

后端 未结 5 596
余生分开走
余生分开走 2021-02-09 12:05

I\'m writing an app that gets a Json list of objects like this:

[
   {
       \"ObjectType\": \"apple\",
       \"ObjectSize\": 35,
       \"ObjectC         


        
5条回答
  •  [愿得一人]
    2021-02-09 12:43

    Define base class and derived classes.

    the use [JSON.net](also available via NuGet)1 to deserialize them.

    I.e.

    class ItemToSell {
     string Type {get;set;}
     string Size {get;set;}
     string Cost {get;set;}
    }
    
    class Book : ItemToSell { ...}
    

    Then deserialize using

    var catalog = JsonConvert.Deserialize>(json);
    

    The deserializer will ignore unexpected properties. Call it again using a specific type to get other properties if you need.

提交回复
热议问题