【问题标题】:Serializing with Newtonsoft.Json使用 Newtonsoft.Json 进行序列化
【发布时间】:2017-04-14 03:54:27
【问题描述】:
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; }
}

我的类中有这样的构造,但我无法将它格式化为 JSON,可能“priceList”将是根对象,并且在根对象下应该有“itemId”作为键值,例如“12345”:其中包含属性“价格”:“123”或“平均”:“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 });

我也尝试了以下方法:

int id = 12345;
int RAVG = 1293;

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

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

我收到这样的错误消息(翻译,由于我自己的语言)

System.NullReferenceException: '不能作为对象的引用 确定对象的实例。'

我真的不明白。

【问题讨论】:

    标签: json json.net


    【解决方案1】:

    您缺少初始化。

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

    【讨论】:

    • 哦。我什至不知道。我应该阅读更多文件。我真的不知道它们也必须像这样单独初始化。我认为我所做的已经足够了。甚至没有意识到这一点。十分感谢!我花了几个小时试图找到解决方案,而您在几分钟内就做出了回应!
    猜你喜欢
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多