【问题标题】:Object reference not set to an instance of an object in deserialize the json data [duplicate]对象引用未设置为反序列化json数据中的对象实例[重复]
【发布时间】:2020-10-26 15:10:23
【问题描述】:

我在反序列化 JSON 数组数据时收到“对象引用未设置为对象的实例”错误。

以下是 SSIS 脚本任务中使用的代码。

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Net;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;



[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
 {
  private long dataLength;

  public override void PreExecute()
   {
    base.PreExecute();
   }

public override void PostExecute()
{
    base.PostExecute();
}

public override void CreateNewOutputRows()
{

    //Get SSIS Variables
    string apiUserName = Variables.APIUsername;
    string apiPassword = Variables.APIPassword;
    //int campaignId = (int)Variables.Campaign;

    //Set Webservice URL
    string wUrl = "My URL Here";
    string base64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(apiUserName + ":" + apiPassword));
    try
    {
        //Call getWebServiceResult to return our WorkGroupMetric array
        Root outPutMetrics = GetWebServiceResult(wUrl, base64);

        //For each group of metrics output records
        //these are the column names defined in output columns in object
        foreach (var metric in outPutMetrics.Rows)
        {
            Output0Buffer.AddRow();

           Output0Buffer.EmployeeReport = metric.EmployeeReport;
            Output0Buffer.EmployeeDisplayName = metric.Employee_DisplayName;
            Output0Buffer.PRPayRunResultPermanentEmployeeNumber = metric.PRPayRunResultPermanent_EmployeeNumber;
            Output0Buffer.OrgUnitShortName = metric.OrgUnit_ShortName;
          

        }

    }
    catch (Exception e)
    {
        //FailComponent(e.ToString());
        if (e.Message != null)
        {
            string ExceptionMessage = e.Message;

        }

    }

}

/// <returns>An array of WorkGroupMetric composed of the de-serialized JSON</returns>
private Root GetWebServiceResult(string wUrl, string base64)
{

    HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);

    httpWReq.Headers.Add("Authorization", "Basic " + base64);
    HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
    Root jsonResponse = null;

    try
    {
        //Test the connection
        if (httpWResp.StatusCode == HttpStatusCode.OK)
        {

            Stream responseStream = httpWResp.GetResponseStream();
             dataLength = httpWResp.ContentLength;

            string jsonString = null;

            //Set jsonString using a stream reader
            using (StreamReader reader = new StreamReader(responseStream))
            {
                jsonString = reader.ReadToEnd().Replace("\\", "");
                reader.Close();
            }
            //Deserialize our JSON
            JavaScriptSerializer sr = new JavaScriptSerializer();
            sr.MaxJsonLength=2147483644;
            jsonResponse = sr.Deserialize<Root>(jsonString);
            

        }
        //Output connection error message
        else
        {
            FailComponent(httpWResp.StatusCode.ToString());

        }
    }
    //Output JSON parsing error
    catch (Exception ex)
    {
        if (ex.Message != null)
        {
            string ExceptionMessage = ex.Message;

        }
    }
    return jsonResponse;

}

/// <summary>
/// Outputs error message
/// </summary>
/// <param name="errorMsg">Full error text</param>
private void FailComponent(string errorMsg)
{
    bool fail = false;
    IDTSComponentMetaData100 compMetadata = this.ComponentMetaData;
    compMetadata.FireError(1, "Error Getting Data From Webservice!", errorMsg, "", 0, out fail);

}

}

以下是来自 JSON2CSHARP.com 的 C# 类

public class Row
{
public string Employee_DisplayName { get; set; }
public string PRPayRunResultPermanent_EmployeeNumber { get; set; }
public string OrgUnit_ShortName { get; set; }

public string EmployeeReport{ get; internal set; }
  }

   public class Data
   {
     public string EmployeeReport{ get; set; }
     public List<Row> Rows { get; set; }
     }



    public class Root
     {

      public List<Row> Rows { get; set; }
      public Data data { get; set; }

       }

能否请您尽快帮我解决问题。 jsonResponse 从 Data 中返回数据,并包含数据。但是在运行foreach循环之后是通过Object reference not set to an instance of an object的错误。

【问题讨论】:

  • 你应该反序列化 Root 而不是 Data 所以它应该是 sr.Deserialize&lt;Root&gt;(jsonString);
  • 您的 JSON 无效 "Plant 2 - Assembly 1"- Assembly 1" 您出于某种原因关闭了报价
  • 为什么不改用Newtonsoft.Json
  • 每当您处理 JSON 并且遇到错误时,第一步是确保它是有效的 JSON,而您的不是。有很多 JSON 验证器,使用它们!
  • #Lou - 使用正确的 JSON 数据更新

标签: c# json deserialization


【解决方案1】:

如果您使用 Root 而不是 Data,则该代码确实有效。将以下代码粘贴到控制台应用程序中,它将正确输出数据:

class Program
{
    static void Main(string[] args)
    {
        var jsonString = "{\"Data\":{\"EmployeeReport\":\"Payroll_Earning_Hours_Detail\",\"Rows\":[{\"Employee_DisplayName\":\"Narasimha Reddy\",\"Permanent_EmployeeNumber\":\"8965594\",\"OrgUnit_ShortName\":\"Plant 2 - Assembly 1\"}]}}";
        Console.WriteLine(Regex.Unescape(jsonString));
        JavaScriptSerializer sr = new JavaScriptSerializer();
        sr.MaxJsonLength = 2147483644;
        Root jsonResponse = sr.Deserialize<Root>(jsonString);
        Console.WriteLine(jsonResponse.Data.EmployeeReport);  // Payroll_Earning_Hours_Detail
        Console.WriteLine(jsonResponse.Data.Rows[0].Permanent_EmployeeNumber);  // 8965594
        Console.ReadLine();
    }
}

public class Row
{
    public string Employee_DisplayName { get; set; }
    public string Permanent_EmployeeNumber { get; set; }
    public string OrgUnit_ShortName { get; set; }
}

public class Data
{
    public string EmployeeReport { get; set; }
    public List<Row> Rows { get; set; }
}

public class Root
{
    public Data Data { get; set; }

}

【讨论】:

  • 感谢 Rich N,我尝试在控制台应用程序中正常工作。但我正在尝试将 json 数据插入到 sql 表中。
  • 好的。在那种情况下,为了让我们帮助您,您需要更详细地向我们展示问题所在,不是吗?也许您可以编辑问题以显示出了什么问题?目前我们有一些似乎可以工作的代码!
  • 嗨 Rich N,我用当前问题编辑了我的问题。你能帮我解决一下吗?
  • 您需要在这里做的是调试代码并尝试自己弄清楚发生了什么。这里没有足够的信息让我们知道。我看不出有什么明显的错误,而且如果不访问数据,我们就无法重现问题。您之前显示的 JSON 不会在此代码中引发异常,但我猜还有其他 JSON 会。
猜你喜欢
  • 1970-01-01
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多