Deserialize JSON to 2 different models

前端 未结 9 1204
眼角桃花
眼角桃花 2021-02-06 23:42

Does Newtonsoft.JSON library have a simple way I can automatically deserialize JSON into 2 different Models/classes?

For example I get the JSON:

[{
  \"g         


        
9条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 00:08

    Since both your objects are the same, wouldn't it make more sense to just have an ID/Name structure of a single base class? If you need to send all the data at the same time, you can restructure your data and use a data transfer object pattern. The JSON object would become

    [{
      "guardian": {
        "id": "1453",
        "name": "Foo Bar"
      },
      "patient": {
        "id" : "938",
        "name": "Foo Bar"
      }
    }]
    

    And your corresponding data objects would be:

    public class Record {
      public int id { get; set; } // or string.  I'm not sure which would be more appropriate
      public string name { get; set;}
    }
    

    and

    public class RecordDto {
      public Record guardian { get; set; }
      public Record patient { get; set; }
    }
    

    And your API would receive a

    List
    

    parameter (since you are passing an array of objects).

提交回复
热议问题