user4738571
user4738571

Reputation:

Serializing with Newtonsoft.Json

public class Prices
{
    public string avg { get; set; }
}

public class PriceID
{
    public string itemId { get; set; }
    public List<Prices> prices { get; set; }
}

public class ObjectPricesRoot
{
    public List<PriceID> pricesList { get; set; }
}

I have such a construct in my classes, but I cannot get it format the JSON likely that the "priceList" will be the root object and under the root object there should be "itemId" as key value like "12345": which contains attribute "prices": "123" or "avg": "123"

ObjectPricesRoot pricesRoot = new ObjectPricesRoot();
PriceID priceId = new PriceID();
Prices prices = new Prices();

int id = 12345;
int RAVG = 1293;
priceId.prices.Add(new Prices { avg = RAVG.ToString() });
pricesRoot.pricesList.Add(new PriceID { itemId = id });

I also tried following:

int id = 12345;
int RAVG = 1293;

prices.avg = RAVG.ToString();
priceId.itemId = id;

priceId.prices.Add(prices);
pricesRoot.pricesList.Add(priceId);

I get such a error message (translated, due my own language)

System.NullReferenceException: 'as a reference to an object can not determine the instance of the object.'

I don't really get it.

Upvotes: 0

Views: 28

Answers (1)

Liu
Liu

Reputation: 982

You are missing initialization.

priceId.prices = new List<Prices>();
pricesRoot.pricesList = new List<PriceID>();

Upvotes: 0

Related Questions