Newtonsoft.Json.JsonSerializationException:转换值时出错,无法将System.String强制转换或转换为DashBoard.DashboardReport

时间:2018-10-05 05:42:20

标签: c# json json.net

我已经编写了将JSON从字符串反序列化为Class(DashBoardReport)对象类型的代码,但是它给了我下面的异常,我签出了JSON结构,它是有效的JSON结构,并且与DashBoardReport Class匹配结构,所以我不明白为什么它给了我与演员相关的异常,请帮忙。

完全例外:

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.

反序列化代码

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

美化的JSON结构,即要反序列化:

{
  "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类结构:

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

        }
    }

DashBoardReportElement类的结构:

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

3 个答案:

答案 0 :(得分:1)

您的异常很可能来自格式错误的JSON字符串。

您的示例代码运行良好。如果我们举一个较小的例子:

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

它将像您示例中的字符串一样再次无问题地序列化到您的类中。但是,如果您有额外的报价:

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

您遇到了麻烦。所以解决方案是修剪那些:

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

作为旁注-在您的示例中,不需要字段支持的属性,您的类可以轻松地重写为

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

答案 1 :(得分:0)

我认为您在此处提供的json是正确的,但是您在实际代码中使用的json是错误的。您可能将json用作

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

您的DashboardReportElement看起来像这样吗?

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

使用List<DashboardReportElement>作为返回类型而不是DashboardReportElement[]数组

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

答案 2 :(得分:0)

我在请求application/json时遇到此错误:

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

如果删除标头,则会收到正确的json。 (我想这是服务器端的错误配置,但此刻我要炸更大的鱼了。)