LINQ to JSON - 无法`。选择`子数据到父对象

时间:2018-03-15 14:34:23

标签: c# json json.net

我正在尝试将一些JSON解析为一个具有另一个类作为其中一个属性的类。我使用Newtonsoft.Json作为我的JSON解析器。

private class OrderModel
{
  public string OrderId {get; set;}
  public string OrderDescription {get; set;}
  public List<OrderDetailModel> OrderItems {get; set;} // Collection of OrderDetails
}

private class OrderDetailModel
{
  public string ProductId {get; set;}
  public string ProductName {get; set;}
  public decimal UnitPrice {get; set;}
  public int Quantity {get; set;}
}

以下是一些示例JSON

{
  ... //JSON data above here
  "transactionData": {
    "orders": [{
        "orderId": 111,
        "orderDescription": "Giant Food Mart",
        "orderItems": [{
            "productId": 65,
            "productName": "Dried Beef",
            "unitPrice": 10.00,
            "quantity": 7
          },
          {
            "productId": 23,
            "productName": "Carrots",
            "unitPrice": 1.25,
            "quantity": 100
          }
        ]
      },
      {
        "orderId": 112,
        "orderDescription": "Bob's Corner Variety",
        "orderItems": [{
            "productId": 523,
            "productName": "Red Licorice",
            "unitPrice": 0.50,
            "quantity": 27
          },
          {
            "productId": 321,
            "productName": "Gummy Worms",
            "unitPrice": 1.50,
            "quantity": 50
          }
        ]
      }
    ]
  }
  ... //JSON data below here
}

我的C#代码用JSON数据填充对象

var parsedJson = JObject.Parse(jsonResponse);
var transactionData = parsedJson["transactionData"]; // Jump to the transactionData node
var orders = transactionData
  .Select(x => new OrderModel
  {
    OrderId = (string)x["orderId"],
    OrderDescription = (string)x["orderDescription"],
    OrderItems = x["orderItems"].Select(y => new OrderDetailModel
    {
      ProductId  = (string)y["productId"], // not being recognized
      ProductName = (string)y["productName"], // not being recognized
      UnitPrice = (decimal)y["unitPrice"], // not being recognized
      Quantity = (int)y["quantity"] // not being recognized
    }).ToList()
  }).ToList();

问题是当我尝试填充OrderDetailModel时。智能感知器无法识别ObjectDetailModel的任何属性。

我错过了我的LINQ语句有什么问题吗?我想使用这种填充OrderModelOrderDetailModel对象的方法,因为属性名称不必与JSON属性名称匹配。我希望在LINQ Lambda语句中进行映射。

更新为了帮助澄清一些评论的答案。我甚至无法编译代码。只要我在OrderDetailModel的其中一个属性中尝试输入,就无法识别。

var parsedJson = JObject.Parse(jsonResponse);
var transactionData = parsedJson["transactionData"]; // Jump to the transactionData node
var orders = transactionData
  .Select(x => new OrderModel
  {
    OrderId = (string)x["orderId"],
    OrderDescription = (string)x["orderDescription"],
    OrderItems = x["orderItems"].Select(y => new OrderDetailModel
    {
      //properties for OrderDetailModel not recognized here
    }).ToList()
  }).ToList();

这个Lambda语句不应该有效吗?

2 个答案:

答案 0 :(得分:1)

首先,你的问题中的班级名称不同于一个。

您已将类声明为OrderDetailsOrderModel以及您使用的代码OrderDetailModelJsonConvert

使用一个名称并使类受保护或不私有。

您的问题的解决方案是使用以下类结构并使用public class Response { [JsonProperty("transactionData")] public TransactionData TransactionData { get; set; } } public class TransactionData { [JsonProperty("orders")] public List<Order> Orders { get; set; } } public class Order { [JsonProperty("orderId")] public string OrderId { get; set; } [JsonProperty("orderDescription")] public string OrderDescription { get; set; } [JsonProperty("orderItems")] public List<OrderDetail> OrderItems { get; set; } // Collection of OrderDetails } public class OrderDetail { [JsonProperty("productId")] public string ProductId { get; set; } [JsonProperty("productName")] public string ProductName { get; set; } [JsonProperty("unitPrice")] public decimal UnitPrice { get; set; } [JsonProperty("quantity")] public int Quantity { get; set; } }

 string jsonResponse = @"{
                  'transactionData': {
                    'orders': [{
                        'orderId': 111,
                        'orderDescription': 'Giant Food Mart',
                        'orderItems': [{
                            'productId': 65,
                            'productName': 'Dried Beef',
                            'unitPrice': 10.00,
                            'quantity': 7
                          },
                          {
                            'productId': 23,
                            'productName': 'Carrots',
                            'unitPrice': 1.25,
                            'quantity': 100
                          }
                        ]
                      },
                      {
                        'orderId': 112,
                        'orderDescription': 'Bob\'s Corner Variety',
                        'orderItems': [{
                            'productId': 523,
                            'productName': 'Red Licorice',
                            'unitPrice': 0.50,
                            'quantity': 27
                          },
                          {
                            'productId': 321,
                            'productName': 'Gummy Worms',
                            'unitPrice': 1.50,
                            'quantity': 50
                          }
                        ]
                      }
                    ]
                  }
                }";
 var transactionData = JsonConvert.DeserializeObject<Response>(jsonResponse);

然后Desrialize

SecCodeCopySigningInformation()

enter image description here

答案 1 :(得分:1)

我得到了LINQ语句来读取你的JSON,你抓住了transactionData但没有得到它下面的订单节点。请参阅评论,其中概述了一些更改:

var orders = transactionData["orders"]
     .Select(x => new OrderModel
     {
         OrderId = (int)x["orderId"],
         OrderDescription = (string)x["orderDescription"],
         OrderItems = x["orderItems"]
         .Select(y => new OrderDetailModel
         {
            ProductId = (string)y["productId"],
            ProductName = (string)y["productName"], 
            UnitPrice = (decimal)y["unitPrice"], // casting to decimal but you have a string
            Quantity = (int)y["quantity"]
          }).ToList()
      });

public class OrderModel
    {
        public int OrderId { get; set; }
        public string OrderDescription { get; set; }
        public List<OrderDetailModel> OrderItems { get; set; } // Collection of OrderDetails
    }



public class OrderDetailModel
    {
        public string ProductId { get; set; }
        public string ProductName { get; set; }
        public decimal UnitPrice { get; set; }
        public int Quantity { get; set; }
    }

.Net小提琴:https://dotnetfiddle.net/bcR7Io