-2

I have JSON like

[
  {
    "Id":"1"
  }, 
  {
    "Id":"2"
  }
]

And I have models

public class ModelList
{
   public List<Model> Models {get; set;}
}

public class Model
{
   public string Id {get; set;}
}

Can I Deserialize this json to ModelList like:

var model = JsonConvert.DeserializeObject<ModelList>(strJson); - This code throw error


var model = JsonConvert.DeserializeObject<List<Model>>(strJson); - This works fine, but I need to deserialize into my model, not List

In other words, I need to bind the array that comes to me in json to the model property

Zerlok
  • 13
  • 4
  • 1
    How about `var model = new ModelList { Models = JsonConvert.DeserializeObject>(strJson) };`? If you really need the serializer to do it on its own there's probably some attribute or custom resolver voodoo that will accomplish it, but there's no need for that unless some code that can't be changed absolutely needs a single class. Note that you could also consider just inheriting (`class ModelList : List`), though inheriting from `List` is [not generally recommended](https://stackoverflow.com/q/21692193/4137916). – Jeroen Mostert Feb 07 '22 at 09:57

1 Answers1

0

try this

ModelList modelList =  new ModelList{
 Models=JsonConvert.DeserializeObject<List<Model>>(strJson)
};

or you can use a model constructor

ModelList modelList = new ModelList (JsonConvert.DeserializeObject<List<Model>>(strJson));

public class ModelList
{
   public List<Model> Models {get; set;}

    public ModelList(List<Model> models)
   {
      Models=models;
   }  
}

or you will have to correct your json according to a ModelList

 {"Models": [
  {
    "Id":"1"
  }, 
  {
    "Id":"2"
  }
]}

and then

ModelList modelList = JsonConvert.DeserializeObject<ModelList>(strJson);
Serge
  • 40,935
  • 4
  • 18
  • 45