簡體   English   中英

對象引用未設置為json中對象錯誤的實例

[英]Object reference not set to an instance of an object error in json

我正在嘗試開發以下格式的json feed

{
    "contacts": [
        {
                "id": "c200",
                "name": "Ravi Tamada",
                "email": "ravi@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },


  ]
}

使用以下代碼

public class Phone
{
    public string mobile { get; set; }
    public string home { get; set; }
    public string office { get; set; }
}

public class Cont
{
    public string sno { get; set; }
    public string name { get; set; }
    public string em { get; set; }
    public string address { get; set; }
    public string gender { get; set; }
    public Phone phone { get; set; }
}

public class RootObject
{
    public List<Cont> contacts { get; set; }
}

var objectToSerialize = new RootObject();
      //  var aa = new Cont();
        objectToSerialize.contacts = new List<Cont> 
                          {
                             new Cont { sno = "test1", name = "index1" , address = "index1",gender="male",em="scd", phone={mobile="ff",home="ff",office="ff"}}
                           //  new Item { name = "test2", index = "index2" }
                          };

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Response.Write(serializer.Serialize(objectToSerialize));

使用此代碼無法獲取我的輸出,我也正在獲取未設置為實例的對象引用。

我已經添加了所有代碼。

任何人幫助我的代碼有什么問題

這是您的對象初始化程序中的問題:

phone={mobile="ff",home="ff",office="ff"}

試圖設置現有 Phone對象的屬性。 換句話說,它正在執行:

var tmp = new Cont();
tmp.sno = "test1";
...
tmp.phone.mobile = "ff";
tmp.phone.home = "ff";
...

...無需將tmp.phone的值設置為非空引用。

您要么想要:

phone=new Phone {mobile="ff",home="ff",office="ff"}

或者您需要更改Cont類以為其提供構造函數以初始化Phone

public Cont()
{
    phone = new Phone();
}

我也強烈建議您對屬性使用.NET命名約定,並為您的類提供一個全名Contact而不是Cont 避免毫無意義地縮寫。

您應該能夠將序列化程序配置為在JSON中使用小寫名稱,而不必使.NET名稱難看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM