简体   繁体   中英

Newtonsoft.Json.JsonSerializationException: Error converting value, Could not cast or convert from System.String to DashBoard.DashboardReport

I have written the code to deserialize JSON from String to Class(DashBoardReport) Object type,but it gives me below exception, I checked out my JSON structure, it is a valid JSON structure and also it is matching with the DashBoardReport Class structure, so I don't understand why its giving me the cast related exception,please help.

Complete Exception:

Newtonsoft.Json.JsonSerializationException: Error converting value "{"Company":"Shyamlal Bros","VoucherType":"PurcOrder","Interval":null,"CurrentPeriodSummary":{"StartDate":"20170401","EndDate":"20170430","Amount":2459250.0,"Monthlygross":0.0},"PreviousPeriodSummary":{"StartDate":null,"EndDate":null,"Amount":0.0,"Monthlygross":0.0},"CurrentPeriodNetAmount":" ","CurrentPeriodDetails":[{"StartDate":"1-Apr-2017","EndDate":"30-Apr-2017","Amount":2459250.0,"Monthlygross":0.0}],"PreviousPeriodDetails":[],"GrowthIndicator":null,"Growth":0.0,"GroupByReport":null,"Error":null}" to type 'DashBoard.DashboardReport'. Path '', line 1, position 570. ---> System.ArgumentException: Could not cast or convert from System.String to DashBoard.DashboardReport.

Code For Deserialization :

string json="{\"Company\":\"Shyamlal Bros\",\"VoucherType\":\"PurcOrder\",\"Interval\":null,\"CurrentPeriodSummary\":{\"StartDate\":\"20170401\",\"EndDate\":\"20170430\",\"Amount\":2459250.0,\"Monthlygross\":0.0},\"PreviousPeriodSummary\":{\"StartDate\":null,\"EndDate\":null,\"Amount\":0.0,\"Monthlygross\":0.0},\"CurrentPeriodNetAmount\":\"\",\"CurrentPeriodDetails\":[{\"StartDate\":\"1-Apr-2017\",\"EndDate\":\"30-Apr-2017\",\"Amount\":2459250.0,\"Monthlygross\":0.0}],\"PreviousPeriodDetails\":[],\"GrowthIndicator\":null,\"Growth\":0.0,\"GroupByReport\":null,\"Error\":null}";
 DashboardReport r=JsonConvert.DeserializeObject<DashboardReport>(json);    
 string jsonMonth = JsonConvert.SerializeObject(r);
 Console.WriteLine(jsonMonth);

Beutified JSON Structure ie to be deserialized:

{
  "Company": "Shyamlal Bros",
  "VoucherType": "PurcOrder",
  "Interval": null,
  "CurrentPeriodSummary": {
    "StartDate": "20170401",
    "EndDate": "20170430",
    "Amount": 2459250,
    "Monthlygross": 0
  },
  "PreviousPeriodSummary": {
    "StartDate": null,
    "EndDate": null,
    "Amount": 0,
    "Monthlygross": 0
  },
  "CurrentPeriodNetAmount": " ",
  "CurrentPeriodDetails": [
    {
      "StartDate": "1-Apr-2017",
      "EndDate": "30-Apr-2017",
      "Amount": 2459250,
      "Monthlygross": 0
    }
  ],
  "PreviousPeriodDetails": [],
  "GrowthIndicator": null,
  "Growth": 0,
  "GroupByReport": null,
  "Error": null
}

DashboardReport Class structure:

public class DashboardReport:ITallyReport
    {

        private string company;
        private string voucherType;
        private string interval;
        private string error;

        private DashboardReportElement currentPeriodSummary;
        private string currentPeriodNetAmount;
        private DashboardReportElement previousPeriodSummary;
        private DashboardReportElement[] currentPeriodDetails;
        private DashboardReportElement[] previousPeriodDetails;

        public DashboardReport()
        {
            currentPeriodSummary = new DashboardReportElement();
            previousPeriodSummary = new DashboardReportElement();
            currentPeriodDetails = new DashboardReportElement[] { };
            previousPeriodDetails = new DashboardReportElement[] { };

        }

        public string Company
        {
            get
            {
                return company;
            }

            set
            {
                company = value;
            }
        }

        public string VoucherType
        {
            get
            {
                return voucherType;
            }

            set
            {
                voucherType = value;
            }
        }

        public string Interval
        {
            get
            {
                return interval;
            }

            set
            {
                interval = value;
            }
        }

        public DashboardReportElement CurrentPeriodSummary
        {
            get
            {
                return currentPeriodSummary;
            }

            set
            {
                currentPeriodSummary = value;
            }
        }

        public DashboardReportElement PreviousPeriodSummary
        {
            get
            {
                return previousPeriodSummary;
            }

            set
            {
                previousPeriodSummary = value;
            }
        }

        public string CurrentPeriodNetAmount { get => currentPeriodNetAmount; set => currentPeriodNetAmount = value; }

        public DashboardReportElement[] CurrentPeriodDetails
        {
            get
            {
                return currentPeriodDetails;
            }

            set
            {
                currentPeriodDetails = value;
            }
        }

        public DashboardReportElement[] PreviousPeriodDetails
        {
            get
            {
                return previousPeriodDetails;
            }

            set
            {
                previousPeriodDetails = value;
            }
        }

        public string GrowthIndicator { get; set; }

        public double Growth { get; set; }

        public DashboardGroupByReport GroupByReport { get; set; }
        public string Error { get => error; set => error = value; }




        //public ReportElement[] Data { get; set; }
        //public string GroupBy { get; set; }


        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);

        }
    }

Structure of DashBoardReportElement Class:

 public class DashboardReportElement
    {
        private string startDate;

        private string endDate;

        private double amount;

        private double monthlygross;

        public DashboardReportElement()
        {

        }
        public string StartDate
        {
            get
            {
                return startDate;
            }

            set
            {
                startDate = value;
            }
        }

        public string EndDate
        {
            get
            {
                return endDate;
            }

            set
            {
                endDate = value;
            }
        }

        public Double Amount
        {
            get
            {
                return amount;
            }

            set
            {
                amount = value;
            }
        }

        public double Monthlygross { get => monthlygross; set => monthlygross = value; }
    }

Most likely your exception is coming from a bad-formatted JSON string.

Your example code works nicely. If we take a smaller example:

string json="{\"Company\":\"Shyamlal Bros\"}";

It will be serialised again into your class without troubles, just like the string from your example. But if you have it with extra quotation:

string json="\"{\"Company\":\"Shyamlal Bros\"}\"";

You are in trouble. So the solution is to trim those:

json = json.Trim("\"".ToCharArray());

As a side note - in your example there is no need for a field-backed properties, your class can be easily rewritten as

public class DashboardReport
{
    public string Company { get; set; }

    public string VoucherType { get; set; } 

    public string Interval { get; set; }

    public DashboardReportElement CurrentPeriodSummary { get; set; }

    public DashboardReportElement PreviousPeriodSummary { get; set; }

    public string CurrentPeriodNetAmount { get; set; }

    public DashboardReportElement[] CurrentPeriodDetails { get; set; }

    public DashboardReportElement[] PreviousPeriodDetails { get; set; }

    public string GrowthIndicator { get; set; }

    public double Growth { get; set; }

    public DashboardGroupByReport GroupByReport { get; set; }

    public string Error { get; set; }

    public string ToJson()
    {
        return JsonConvert.SerializeObject(this);
    }
}

i think the json you have provided here is correct but the json which you are using in your actual code is bad. You may be using json as

string json="\"{\"Company\":\"Shyamlal Bros\",\"VoucherType\":\"PurcOrder\",\"Interval\":null,\"CurrentPeriodSummary\":{\"StartDate\":\"20170401\",\"EndDate\":\"20170430\",\"Amount\":2459250.0,\"Monthlygross\":0.0},\"PreviousPeriodSummary\":{\"StartDate\":null,\"EndDate\":null,\"Amount\":0.0,\"Monthlygross\":0.0},\"CurrentPeriodNetAmount\":\"\",\"CurrentPeriodDetails\":[{\"StartDate\":\"1-Apr-2017\",\"EndDate\":\"30-Apr-2017\",\"Amount\":2459250.0,\"Monthlygross\":0.0}],\"PreviousPeriodDetails\":[],\"GrowthIndicator\":null,\"Growth\":0.0,\"GroupByReport\":null,\"Error\":null}\"";  
// Extra Quatation Marks in json

Is Your DashboardReportElement look like this ?

public class DashboardReportElement
{
   public string StartDate { get; set; }
   public string EndDate { get; set; }
   public int Amount { get; set; }
   public int Monthlygross { get; set; }
}

Use List<DashboardReportElement> as a return type Instead of DashboardReportElement[] array

Ex -

 private DashboardReportElement currentPeriodSummary;
 private string currentPeriodNetAmount;
 private DashboardReportElement previousPeriodSummary;
 private List<DashboardReportElement> currentPeriodDetails;   // made List instead of array
 private List<DashboardReportElement> previousPeriodDetails;   // made List instead of Array

I got this error when requesting application/json :

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

If I remove the header I received correct json. (I guess it is a misconfiguration at the server-side, but at te moment I've got bigger fish to fry.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM