0

I have nested JObject:

{
"model": {
"id": "1",
"amount": "1.00",
"details": {
    "tax": "0.10",
    "order": "DFG456"
},
"lineItems": [
  {
    "commodityCode": "abc",
    "unitOfMeasure": "pnd",
    "quantity": "1",
    "uomCost": "1.00",
    "taxAmount": "0.10",
    "itemTotalAmount": "0.10"
  },{
    "commodityCode": "xyz",
    "unitOfMeasure": "pnd",
    "quantity": "2",
    "uomCost": "1.00",
    "taxAmount": "0.10",
    "itemTotalAmount": "0.10"
  }
]

} }

I'm trying to deserialize it into my ViewModel that structured like that:

public class MyViewModel {
    int id { get; set;}
    decimal amount { get; set; }
    DetailsVm details { get; set;} 
    List<DetailItem> DetailsItemsList { get; set; }
}

I have no problem desereializing top model and child details object using dynamic object like that:

var model = json.model.ToObject<MyViewModel>;
var details = json.serviceInfo.ToObject<DetailsVm>;

However, I can't find a way to extract the list of DetailsItems from json. Property is null in the model. Any advice on how to extract the child enumerable object would be greatly appreciated. Array, List, just enumerable - either way would work.

lentyai
  • 534
  • 1
  • 9
  • 22

2 Answers2

1

Make the model as follows:

public class MyViewModel {
    int id { get; set;}
    decimal amount { get; set; }
    DetailsVm details { get; set;} 
    IEnumerable<DetailItem> DetailsItemsList { get; set; }
}

Then change the json to send a collection NAMED DetailsItemsList.

The model's attribute name must match the name given in the json.

TheSilence
  • 342
  • 1
  • 3
  • 11
  • Yep, the difference in the name was a problem. Thanks! However the solution below works as well - even with the difference in naming. Will take your answer, though. – lentyai Jul 14 '15 at 20:29
0

Found an answer here: Deserialize JSON into C# dynamic object?. Answer by Tom Peplow best suets my needs:

using Newtonsoft.Json.Linq; model = JObject.Parse(jsonString);

Community
  • 1
  • 1
lentyai
  • 534
  • 1
  • 9
  • 22