简体   繁体   English

如何使用多个类来修复Json中的反序列化<null in object reference>

[英]How to fix deserialization in Json with multiple classes <null in object reference>

I am able to deserialise root object but cannot access the underlying classes I receive a null reference exception. 我能够反序列化根对象,但无法访问我收到空引用异常的基础类。 I need to extract the fields from the orderitems class. 我需要从orderitems类中提取字段。

in the following scenario the derserialization works great and can extract fields attached to items 在以下场景中,derserialization工作得很好,可以提取附加到项目的字段

 var  Sresponse = JsonConvert.DeserializeObject<RootObject>(json);
                  Console.WriteLine(Sresponse.items);

However doesn't work here 但是在这里不起作用

 var  Sresponse = JsonConvert.DeserializeObject<Item>(json);
                  Console.WriteLine(Sresponse.orderitems);

Error message : System.NullReferenceException: Object reference not set to an instance of an object 错误消息:System.NullReferenceException:对象引用未设置为对象的实例

please help. 请帮忙。

  Json String 
{
    "totalcount": 103952,
    "items": [
        {
            "orderid": 113951,
            "email": "",
            "namefirst": "",
            "namelast": "",
            "company": "",
            "moneyfinal_net": "95.92",
            "moneyfinal_vat": "23.98",
            "moneytotal_gross_roundoff": "0.00",
            "moneytotal_gross_all": "119.90",
            "checkouttypename": "Card",
            "deliverytypename": "",
            "orderdate": 1554836745,
            "orderstateid": 10,
            "paymentstateid": 20,
            "ordertypeid": 10,
            "registerid": "{AD16AEE2-235F-318A-4323-6B63EC2C40E7}",
            "warehouseid": 18,
            "datereserved": null,
            "currencycode": "NOK",
            "additionaldata": {
                "pos-timezone": "Europe/Oslo",
                "pos-staff-externalid": "4654"
            },
            "orderitems": [
                {
                    "orderitemid": 0,
                    "orderitemtype": 10,
                    "productid": 5486,
                    "productname": "Test",
                    "sku": "320991800016",
                    "productattributes": "",
                    "externalinput": "",
                    "externalinputtitle": "",
                    "unitlabel": "ST",
                    "quantity": 1,
                    "decimalunitquantity": null,
                    "moneynetpriceperunit": "63.92",
                    "moneypriceorg": "0.00",
                    "vatvalue": 25,
                    "deliveryinfo": "",
                    "moneyitemtotal_net": "63.92",
                    "moneyitemtotal_vat": "15.98",
                    "voucherid": 0,
                    "vouchercode": "",
                    "vouchername": "",
                    "moneyoriginalprice": "63.92",
                    "moneydiscountedprice": "0.00",
                    "moneydiscount": "0.00",
                    "salestaxes": [],
                    "additionaldata": {},
                    "decimalquantitytotal": "1.000",
                    "moneynetpriceperquantity": "63.92"
                },


Classes 

public class Orderitem
    {
        public int orderitemid { get; set; }
        public int orderitemtype { get; set; }
        public int productid { get; set; }
        public string productname { get; set; }
        public string sku { get; set; }
        public string productattributes { get; set; }
        public string externalinput { get; set; }
        public string externalinputtitle { get; set; }
        public string unitlabel { get; set; }
        public int quantity { get; set; }
        public object decimalunitquantity { get; set; }
        public string moneynetpriceperunit { get; set; }
        public string moneypriceorg { get; set; }
        public int vatvalue { get; set; }
        public string deliveryinfo { get; set; }
        public string moneyitemtotal_net { get; set; }
        public string moneyitemtotal_vat { get; set; }
        public int voucherid { get; set; }
        public string vouchercode { get; set; }
        public string vouchername { get; set; }
        public string moneyoriginalprice { get; set; }
        public string moneydiscountedprice { get; set; }
        public string moneydiscount { get; set; }
        public List<object> salestaxes { get; set; }
        public string decimalquantitytotal { get; set; }
        public string moneynetpriceperquantity { get; set; }

    }

    public class Item
    {
        public int orderid { get; set; }
        public string moneyfinal_net { get; set; }
        public string checkouttypename { get; set; }
        public int orderdate { get; set; }
        public int orderstateid { get; set; }
        public string registerid { get; set; }
        public int warehouseid { get; set; }
        public string currencycode { get; set; }
        public List<Orderitem>  orderitems { get; set; }



        public class RootObject
    {
        public int totalcount { get; set; }
        public List<Item> items { get; set; }
}

Firstly, after fixing your JSON string which is incorrectly defined in the question and then using this Model structure in your case: 首先,修复问题中未正确定义的JSON字符串,然后在您的案例中使用此Model结构:

Note: For parsing Property names with special characters (like - ) in your JSON, you can use the JSONProperty attribute as shown below to parse out those properties. 注意:要在JSON中解析具有特殊字符(如- )的Property名称,可以使用如下所示的JSONProperty属性来解析这些属性。

public class Additionaldata
{
[JsonProperty(PropertyName = "pos-timezone")]
public string postimezone { get; set; }
[JsonProperty(PropertyName = "pos-staff-externalid")]
public string posstaffexternalid { get; set; }
}

public class Orderitem
{
    public int orderitemid { get; set; }
    public int orderitemtype { get; set; }
    public int productid { get; set; }
    public string productname { get; set; }
    public string sku { get; set; }
    public string productattributes { get; set; }
    public string externalinput { get; set; }
    public string externalinputtitle { get; set; }
    public string unitlabel { get; set; }
    public int quantity { get; set; }
    public object decimalunitquantity { get; set; }
    public string moneynetpriceperunit { get; set; }
    public string moneypriceorg { get; set; }
    public int vatvalue { get; set; }
    public string deliveryinfo { get; set; }
    public string moneyitemtotal_net { get; set; }
    public string moneyitemtotal_vat { get; set; }
    public int voucherid { get; set; }
    public string vouchercode { get; set; }
    public string vouchername { get; set; }
    public string moneyoriginalprice { get; set; }
    public string moneydiscountedprice { get; set; }
    public string moneydiscount { get; set; }
    public List<object> salestaxes { get; set; }
    public Additionaldata additionaldata { get; set; }
    public string decimalquantitytotal { get; set; }
    public string moneynetpriceperquantity { get; set; }
}

public class Item
{
    public int orderid { get; set; }
    public string email { get; set; }
    public string namefirst { get; set; }
    public string namelast { get; set; }
    public string company { get; set; }
    public string moneyfinal_net { get; set; }
    public string moneyfinal_vat { get; set; }
    public string moneytotal_gross_roundoff { get; set; }
    public string moneytotal_gross_all { get; set; }
    public string checkouttypename { get; set; }
    public string deliverytypename { get; set; }
    public int orderdate { get; set; }
    public int orderstateid { get; set; }
    public int paymentstateid { get; set; }
    public int ordertypeid { get; set; }
    public string registerid { get; set; }
    public int warehouseid { get; set; }
    public object datereserved { get; set; }
    public string currencycode { get; set; }
    public Additionaldata additionaldata { get; set; }
    public List<Orderitem> orderitems { get; set; }
}

public class RootObject
{
    public int totalcount { get; set; }
    public List<Item> items { get; set; }
}

And finally deserializing it: 最后反序列化:

using System;
using Newtonsoft.Json;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string json=@"{'totalcount':103952,'items':[{'orderid':113951,'email':'','namefirst':'','namelast':'','company':'','moneyfinal_net':'95.92','moneyfinal_vat':'23.98','moneytotal_gross_roundoff':'0.00','moneytotal_gross_all':'119.90','checkouttypename':'Card','deliverytypename':'','orderdate':1554836745,'orderstateid':10,'paymentstateid':20,'ordertypeid':10,'registerid':'{AD16AEE2-235F-318A-4323-6B63EC2C40E7}','warehouseid':18,'datereserved':null,'currencycode':'NOK','additionaldata':{'pos-timezone':'Europe/Oslo','pos-staff-externalid':'4654'},'orderitems':[{'orderitemid':0,'orderitemtype':10,'productid':5486,'productname':'Test','sku':'320991800016','productattributes':'','externalinput':'','externalinputtitle':'','unitlabel':'ST','quantity':1,'decimalunitquantity':null,'moneynetpriceperunit':'63.92','moneypriceorg':'0.00','vatvalue':25,'deliveryinfo':'','moneyitemtotal_net':'63.92','moneyitemtotal_vat':'15.98','voucherid':0,'vouchercode':'','vouchername':'','moneyoriginalprice':'63.92','moneydiscountedprice':'0.00','moneydiscount':'0.00','salestaxes':[],'additionaldata':{},'decimalquantitytotal':'1.000','moneynetpriceperquantity':'63.92'}]}]}";
        var  Sresponse = JsonConvert.DeserializeObject<RootObject>(json);
        Console.WriteLine(Sresponse.totalcount);

        foreach(var result in Sresponse.items)
        {    
         Console.WriteLine(result.moneyfinal_net);
         Console.WriteLine(result.additionaldata.postimezone);
         foreach(var result1 in result.orderitems)
          {
            Console.WriteLine(result1.orderitemid);
            Console.WriteLine(result1.orderitemtype);
            Console.WriteLine(result1.productid);
            Console.WriteLine(result1.productname); 
            Console.WriteLine(result1.sku);                     
          }
       }
    }
}

Outputs: 输出:

103952
95.92
Europe/Oslo
0
10
5486
Test
320991800016

Working Example: https://dotnetfiddle.net/kGXBQ0 工作示例: https//dotnetfiddle.net/kGXBQ0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM