类创建者输入多个类构造函数

时间:2018-08-27 10:14:18

标签: c# json list class

我有这样的代码:

public class Paket
{
    public int PaketID { get { return _PaketID; } set { _PaketID = value; } }
    public int ProizvodID { get { return _ProizvodID; } set { _ProizvodID = value; } }
    public double Kolicina { get { return _Kolicina; } set { _Kolicina = value; } }
    public double CenaBezPdv { get { return _CenaBezPdv; } set { _CenaBezPdv = value; } }

    private int _PaketID;
    private int _ProizvodID;
    private double _Kolicina;
    private double _CenaBezPdv;

    public string _errorMessage { get; set; }

    private Paket()
    {

    }
    public Paket(int proizvodID)
    {
        if (proizvodID == null) { throw new Exception("ProizvodID ne moze biti NULL!"); }

        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

        string url = "https://www.new.termodom.rs/Php/Proizvodi/Paketi/GetOne.php?proizvodid=" + proizvodID;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();

        switch (resp)
        {
            case "0":  //Nije pronadjen proizvod
                _errorMessage = "Paket nije pronadjen u web bazi!";
                break;
            default:
                Paket p = JsonConvert.DeserializeObject<Paket>(resp);
                this._PaketID = p.PaketID;
                this._ProizvodID = p.ProizvodID;
                this._Kolicina = p.Kolicina;
                this._CenaBezPdv = p.CenaBezPdv;
                break;
        }
    }

    public static List<Paket> SviPaketi(int ProizvodID)
    {
        List<Paket> list = new List<Paket>();

        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

        string url = "https://www.new.termodom.rs/Php/Proizvodi/Paketi/GetAll.php?proizvodid=" + ProizvodID;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();

        switch (resp)
        {
            case "0":  //Nije pronadjen proizvod
                break;
            default:
                list = JsonConvert.DeserializeObject<List<Paket>>(resp);
                break;
        }
        return list;
    }
}

当我运行类似List<Proizvod> myList = Proizvod.SviPaketi(139)的函数时,我遇到了一些错误(我现在不知道它是哪一个,但是对于我的问题来说并不重要)。

当我开始调试时,我发现JsonConvert.DeserializeObject<List<Paket>>(resp);不仅输入private Paket(),它为空,而且public Paket(int proizvodID),其中包含一些代码。

所以我的问题是为什么当我没有向其传递任何参数时,JsonConvert.DeserializeObject<List<Paket>>(resp);触发了public Paket(int proizvodID)

1 个答案:

答案 0 :(得分:1)

JSON反序列化器将首选公共构造函数。但是,您可以使用ConstructorHandling使用私有构造函数。选中此example