-2

I have 3 class like below.

[Serializable]
public class Classa {
  public list<Object> list {get; set;}
}

[Serializable]
public class Classb {
  public string name {get; set;}
  public string nickname {get; set;}
}


[Serializable]
public class Classc {
  public string type {get; set;}
  public string price {get; set;}
}

In my program, I want to cast List<Object> to List<Classb> or List<Classc> when I pass the JSON structure matching with Classb or Classc... is there any way to cast it?

[HttpPost]
[ActionName("Import")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public Object Import([FromBody]Classa ImportData)
{

  List<Classb> blist = a.list.Cast<Classb>().toList();

}

It throws:

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Classb'

I have tried :

List<Classb> blist = aOfType<Classb>().ToList();

Success but no value..

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
cheuk law
  • 35
  • 7

1 Answers1

0

In Classa you have a list with Objects, but you want a list with Classb. So change this

[Serializable]
public class Classa{
list<Object> list{get;set;}
}

to

[Serializable]
public class Classa{
list<Classb> list{get;set;}
}

And this

 List<Classb> blist = a.list.Cast<Classb>().toList();

Can be

List<Classb> blist = a.list;

EDIT: You have a typo her

publc class Classb{
H. Hakvoort
  • 161
  • 1
  • 2
  • 14
  • I know that's one of solution.. but i have other class for example classc.. I want to put it into list too.. So that I can not change to list btw thanks you – cheuk law Oct 19 '17 at 07:13
  • If you want to do that, you can let Classa have 2 lists, with Classb and Classc. But if you really want Classa to only have 1 list. You make a new ClassSuper and make Classb and Classc extend from ClassSuper. Classa will than have a list with ClassSuper – H. Hakvoort Oct 19 '17 at 07:17