I am trying to parse the JSON but it is giving me error as Object Reference not set to instance of an object what i am trying is JSON:
[
{"Product":"Product 1",
"Origins":
[
{"Origin":"XXX QQ",
"Details":
[
{"Seller":"Name","Seller_Rate":"256","Saller_QTY":"20","Buyer":"Name","Buyer_Rate":"256","Buyer_QTY":"20"},
{"Seller":"Name","Seller_Rate":"256","Saller_QTY":"20","Buyer":"Name","Buyer_Rate":"256","Buyer_QTY":"20"}
]
},
{"Origin":"ADAMI Oil",
"Details":
[
{"Seller":"Name","Seller_Rate":"256","Saller_QTY":"20","Buyer":"Name","Buyer_Rate":"256","Buyer_QTY":"20"},
{"Seller":"Name","Seller_Rate":"256","Saller_QTY":"20","Buyer":"Name","Buyer_Rate":"256","Buyer_QTY":"20"}
]
}
]
},
{"Product":"Product 2",
"Origins":
[
{"Origin":"YYY pp",
"Details":
[
{"Seller":"Name","Seller_Rate":"256","Saller_QTY":"20","Buyer":"Name","Buyer_Rate":"256","Buyer_QTY":"20"},
{"Seller":"Name","Seller_Rate":"256","Saller_QTY":"20","Buyer":"Name","Buyer_Rate":"256","Buyer_QTY":"20"}
]
},
{"Origin":"PQR CCC",
"Details":
[
{"Seller":"Name","Seller_Rate":"256","Saller_QTY":"20","Buyer":"Name","Buyer_Rate":"256","Buyer_QTY":"20"},
{"Seller":"Name","Seller_Rate":"256","Saller_QTY":"20","Buyer":"Name","Buyer_Rate":"256","Buyer_QTY":"20"}
]
}
]
}
]
My Object Class that holds the JSON Values:
public class Products
{
public List<Origins> ListOrigin { get; set; }
public string PRODUCT { get; set; }
}
public class Origins
{
public string Origin { get; set; }
public List<Details> ListDetails { get; set; }
}
public class Details
{
public string Seller { get; set; }
public string Seller_Rate { get; set; }
public string Saller_QTY { get; set; }
public string Buyer { get; set; }
public string Buyer_Rate { get; set; }
public string Buyer_QTY { get; set; }
}
call to web-service and parsing :
string responsejson = await client.GetStringAsync(Constants.url_getproducts);
res = JsonConvert.DeserializeObject<List<Products>>(responsejson);
try
{
foreach (Products p in res)
{
Log.Debug("Login1", p.PRODUCT);
foreach (Origins o in p.ListOrigin)
{
Log.Debug("Login1", o.Origin);
}
}
}
catch (Exception e){
Log.Debug("Login e", e.Message);
Log.Debug("Login e", e.StackTrace);
}
Here when i am trying to parse it in foreach, Log.Debug("Login1", p.PRODUCT); this gives Product properly but for Origins it says
Object reference not set to an instance of an object.
One Solution i got is:
try
{
root = JsonConvert.DeserializeObject<List<Products>>(responsejson);
Log.Debug("Login",Convert.ToString(root.Count));
for(int i=0;i<root.Count;i++)
{
Log.Debug("Login", "=============================");
Log.Debug("Login", root[i].PRODUCT);
for(int j=0;j<root[i].Origins.Count;j++)
{
Log.Debug("Login"," "+root[i].Origins[j].Origin);
for(int k=0;k<root[i].Origins[j].Details.Count;k++)
{
Log.Debug("Login", " Buy " + root[i].Origins[j].Details[k].Buyer+" BUY_QTY "+ root[i].Origins[j].Details[k].Buyer_QTY);
}
}
Log.Debug("Login", "=============================");
}
}