无法转换类型' Newtonsoft.Json.Linq.JObject'到复杂类型

时间:2017-08-16 13:57:35

标签: c# json casting json.net

我的json如下,

 <div class="container">
<div class="col-md-6">
    <div class="row">
        <div class="col-md-2">
            <h2>Wiadomosci</h2>
        </div>
    </div>

</div>>

<div class="section">
    <h3>{{headingTitle}}</h3>
    <div>
        <ul type="square">
            <li>Luke</li>
            <li>Darth</li>
            <li>Anakin</li>
            <li>Leia</li>
        </ul>
    </div>
</div>

<div class="panel panel-default" ng-repeat="message in messages">

    <div class="row">
        <div class="col-md-2">
            <div class="panel-default"> {{message.id}}</div>
        </div>
        <div class="col-md-2">
            <div class="panel-default"> {{message.message}}</div>
        </div>
    </div>>
</div>
 </div>

和复杂类型

{
  "H": "Macellum",
  "M": "Receive",
  "A": [
    {
      "CustomerId": "172600",
      "OrderId": "69931",
      "OrderStatus": "E0",
      "Buy": "A"
    }
  ]
}

我正在尝试演员如下,

public class OrderStats
{
    public string CustomerId { get; set; }
    public string OrderId { get; set; }
    public string OrderStatus { get; set; }
    public string Buy { get; set; }
}

但错误如下

  

无法转换类型&#39; Newtonsoft.Json.Linq.JObject&#39;到OrderStatus

2 个答案:

答案 0 :(得分:15)

这个怎么样?

var str = "YOUR_JSON_HERE";
var obj = JsonConvert.DeserializeObject<dynamic>(str);
OrderStats info = ((JArray)obj.A)[0].ToObject<OrderStats>();

答案 1 :(得分:1)

我发现这样的解决方案有点琐碎,

dynamic obj = JsonConvert.DeserializeObject<dynamic>(message);
OrderStats info = JsonConvert.DeserializeObject<OrderStats>(JsonConvert.SerializeObject(obj.A[0]));