无法使用jsonconverter更新现有的json列表

时间:2017-08-21 11:30:32

标签: c# json.net realm

我正在尝试在json中添加字段,同时反序列化来自服务器的响应,然后将其存储到数据库中

这是Response的模型

 public class Response : RealmObject
    {

        [JsonConverter(typeof(QuotationConverter))]
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public IList<Quotation> quotationsList { get; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public IList<Order> ordersList { get; }
    }

QuotationConverter代码,我从另一个json获取客户名称并将其存储到报价单中

 protected override IList<Quotation> parseArray(Type objectType, JArray jsonArray)
        {

            try
            {
                Realm realm = Realm.GetInstance();
                foreach (JObject data in jsonArray)
                {

                    String customerId = data.GetValue("customerId").ToString();
                    Customer customer = realm.All<Customer>().Where(c => c.customerId == Java.Lang.Long.ParseLong(customerId)).FirstOrDefault();
                    if (customer != null)
                    {
                        String customerName = customer.customerName;
                        data.Add("customerName", customerName);
                    }

                }

                realm.Dispose();
                var quotationsList = jsonArray.ToObject<IList<Quotation>>();

                List<Quotation> quotation = new List<Quotation>(quotationsList);

                return quotationsList;
            }
            catch(Exception e)
            {

                Debug.WriteLine(" exception "+e.StackTrace);
            }

            return null;
        }

        protected override Quotation parseObject(Type objectType, JObject jsonObject)
        {
            throw new NotImplementedException();
        }
    }

这里是JsonConverter

 public abstract class JsonConverter<T> : Newtonsoft.Json.JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(JsonConverter<T>));

        }

        protected abstract T parseObject(Type objectType, JObject jsonObject);

        protected abstract IList<T> parseArray(Type objectType, JArray jsonArray);
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {

            try
            {              
               var jsonArray = JArray.Load(reader);
               var data=  parseArray(objectType, jsonArray);              
               return data;

            }
            catch(Exception e)
            {
                Debug.WriteLine(e.StackTrace);
            }
            return null;

        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {

            Debug.WriteLine("Mo " + value);


        }
    }

the issue is when i am getting Response object inside that quotationsList is coming blank.

Json从服务器

收到
quotationsList: [
  {
    "account": null,
    "contactId": 0,
    "currency": "USD",
    "customerId": 5637144583,
    "deliveryAddress": "19TH and Edwardsville RD (RT203)\nGranite City,IL62040\nUSA",
    "expiryDate": "2017-09-04",
    "followUpDate": "2017-09-01",
    "mQuotationId": null,
    "opportunityId": 0,
    "postedOn": null,
    "prospectId": 0,
    "quotationFor": null,
    "quotationId": 5637155076,
    "quotationName": "United States Steel",
    "quotationNumber": "UST1-000022",
    "quotationStatus": "Confirmed",
    "requestReceiptDate": "2017-08-05",
    "requestShipDate": "2017-08-05",
    "siteId": "GLEN1",
    "wareHouseId": "37"
  }

预期json

quotationsList: [
  {
    "account": null,
    "contactId": 0,
    "currency": "USD",
    "customerId": 5637144583,
    "deliveryAddress": "19TH and Edwardsville RD (RT203)\nGranite City,IL62040\nUSA",
    "expiryDate": "2017-09-04",
    "followUpDate": "2017-09-01",
    "mQuotationId": null,
    "opportunityId": 0,
    "postedOn": null,
    "prospectId": 0,
    "quotationFor": null,
    "quotationId": 5637155076,
    "quotationName": "United States Steel",
    "quotationNumber": "UST1-000022",
    "quotationStatus": "Confirmed",
    "requestReceiptDate": "2017-08-05",
    "requestShipDate": "2017-08-05",
    "siteId": "GLEN1",
    "wareHouseId": "37",
    "customerName":"Jhon Caro"
  }

报价模型

 public class Quotation : RealmObject , IMaster, IMedia, IProduct
    {
        [PrimaryKey]
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public String mQuotationId { get; set; } = Guid.NewGuid().ToString();

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public long quotationId { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public String customerName { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string quotationName { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string quotationNumber{ get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string deliveryAddress { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string expiryDate { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string requestShipDate { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string requestReceiptDate { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public long prospectId { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string followUpDate { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public long opportunityId { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string postedOn { get; set; }



    }

已更新

protected override IList<Quotation> parseArray(Type objectType, JArray jsonArray)
{

    try
    {
        Realm realm = Realm.GetInstance();
        var data = jsonArray.ToObject<IList<Quotation>>();
        List<Quotation> quotationList = new List<Quotation>(data);



        foreach (Quotation quotation in quotationList)
        {

            long customerId = quotation.customerId;
            Customer customer = realm.All<Customer>().Where(c => c.customerId == customerId).FirstOrDefault();
            if (customer != null)
            {
                String customerName = customer.customerName;
                quotation.customerName = customerName;
            }

        }

        realm.Dispose();


        return quotationList;
    }
    catch(Exception e)
    {

        Debug.WriteLine(" exception "+e.StackTrace);
    }

    return null;
}

enter image description here

这就是我的反序列化被称为

的方式
  

响应responseData = await Task.Run(()=&gt;   JsonConvert.DeserializeObject(内容));

3 个答案:

答案 0 :(得分:2)

这里的问题不是JSON反序列化或添加到json数组,问题是你没有来自DataBase的记录。

你正在使用这个:

def close_current_and_open_other():
    # code to close the current: destroy(), etc...
    # code to open the second program

btnLearn = Button(container2, image=imgLearnBtn, command=close_current_and_open_other).pack(side=BOTTOM, padx=100)

FirstOrDefault 预计查询会返回零个或多个项目,但您只想访问代码中的第一个项目(即您不确定是否存在具有给定密钥的项目)

将其更改为 long customerId = quotation.customerId; Customer customer = realm.All<Customer>().Where(c => c.customerId == customerId).FirstOrDefault(); if (customer != null) { String customerName = customer.customerName; quotation.customerName = customerName; } 并查看是否会抛出异常,如果是,那么这是您的问题而且您的问题:

First();

返回不正确的数据。

答案 1 :(得分:2)

public class Response : RealmObject
{
    //JsonConverter attribute should be decorating 'Quotation' class
    //[JsonConverter(typeof(QuotationConverter))]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public IList<Quotation> quotationsList { get; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public IList<Order> ordersList { get; }
}

答案 2 :(得分:1)

我相信您的转换器的这种方法不正确

public override bool CanConvert(Type objectType)
{
    return (objectType == typeof(JsonConverter<T>));
}
在这种情况下,

objectType的类型为IList<Quotation>,而不是JsonConverter<IList<Quotation>>。我相信这应该是:

public override bool CanConvert(Type objectType)
{
    return (objectType == typeof(T));
}

编辑:虽然我确实认为这是不正确的,但我不再相信这是问题的根本原因。我已经完全重现了这个问题,修复就是改变这一行。

public IList<Quotation> quotationsList { get; }

public IList<Quotation> quotationsList { get; set; }

JsonConvert需要一个公共设置器才能为属性赋值。

我也改变了这一行

Response responseData = await Task.Run(() => JsonConvert.DeserializeObject(content));

Response responseData = await Task.Run(() => JsonConvert.DeserializeObject<Response>(content));

这告诉DeserializeObject调用哪个类尝试反序列化。