使用Newtonsoft.Json进行序列化

时间:2017-04-13 19:44:22

标签: json json.net

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let TransactionSchema = new Schema({
    ...
});

module.exports = TransactionSchema; 

我在我的类中有这样的构造,但我无法得到JSON格式可能“priceList”将成为根对象,并且在根对象下应该有“itemId”作为键值,如“12345”:其中包含属性“price”:“123”或“avg”:“123”

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; }
}

我也尝试过:

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 });

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

  

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

我真的不明白。

1 个答案:

答案 0 :(得分:0)

您缺少初始化。

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