5 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以執(zhí)行以下操作之一:
List<RootObject> rootObj = new List<RootObject>();
var newObj=new RootObject()
{
code = "success_04",
msg = "Access granted"
};
rootObj.Add(newObj);
List<RootObject> rootObj1 = new List<RootObject>()
{
new RootObject()
{
code = "success_04",
msg = "Access granted"
}
};
接著
JsonRes.Message = rootObj;

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
您正在像處理數(shù)組一樣處理列表,這是行不通的,您需要使用該Add方法,例如
rootObj.Add(new RootObj{
code = "success_04",
msg = "Access granted"
});
您還可以使用該AddRange方法添加多個(gè)對(duì)象,例如
rootObj.AddRange(new List<RootObj>{new RootObj{
code = "success_04",
msg = "Access granted"
}, new RootObj{
code = "success_05",
msg = "Access denied"
}});

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
直接訪問(wèn)您的AuthJsonResponses實(shí)例。首先,更新該類以使其Message具有私有設(shè)置器并將其實(shí)例化為L(zhǎng)ist<RootObject>
public class AuthJsonResponses
{
public int Code { get; set; }
public string Jwt { get; set; }
public List<RootObject> Messages { get; private set; } = new List<RootObject>();
}
public class RootObject
{
public string msg { get; set; }
public string code { get; set; }
}
在您的代碼中,直接將對(duì)象添加到Message屬性中。我建議將其重命名為Messages以表明它是一個(gè)集合
jsonRes.Messages.Add(new RootObject{msg ="Access granted", code="success_04"});

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
您面臨的問(wèn)題是您在初始化列表之后引用列表的第一個(gè)元素!初始化本身只是創(chuàng)建List類的對(duì)象,它不創(chuàng)建任何元素!
因此,您必須自己創(chuàng)建RootObject類的對(duì)象,然后將其添加到列表中:
// create object
var r = new RootObject();
r.code = "success_04";
r.msg = "Access granted";
// add it to list
rootObj.Add(r);

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
當(dāng)您List實(shí)際使用時(shí),您可以使用從類繼承的方法IEnumerable,因?yàn)?List 是 IEnumerable 的實(shí)現(xiàn)。
你可以這樣做:
List<RootObject> rootObj = new List<RootObject>();
//delete this---- rootObj[0].code = "success_04";
//delete this---- rootObj[0].msg = "Access granted";
//use this
rootObj.Add(new RootObject{
code = "success_04",
msg = "Access Granted"
})
JsonRes.Message = rootObj;
- 5 回答
- 0 關(guān)注
- 179 瀏覽
添加回答
舉報(bào)