不支持JSon Type在C#中对数组进行反序列化

时间:2018-08-13 10:46:36

标签: c# json ssis

我以前使用的一些代码有问题,我确定自己只是傻子,但我找不到原因。

我得到的错误是“数组反序列化不支持Type'ScriptMain + Imports'。”

using System;
using System.Net;
using System.Collections.Generic;
using System.Web.Script.Serialization;

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]

public class ScriptMain : UserComponent

{

    string json;

    public override void PreExecute()

    {
        base.PreExecute();
        string url = this.Variables.apiurl; ;
        json = DownloadJson(url);
   }



    public override void CreateNewOutputRows()

    {

        JavaScriptSerializer serialize = new JavaScriptSerializer();

        Imports imports = (Imports)serialize.Deserialize(json, typeof(Imports));

        foreach (var contentType in imports.contents)

        {
            Output0Buffer.name = contentType.name;
        }

    }

    public static string DownloadJson(string downloadURL)

    {
        using (WebClient client = new WebClient())
        {
            return client.DownloadString(downloadURL);
        }
    }

   
    public class Imports
    {
        public List<Contents> contents { get; set; }
    }


    public class Contents
    {
        public string name { get; set; }
    }

}

我觉得唯一的不同是,在此Json导入中没有Root身份,但是我认为我已经使用公共类Imports解决了这个问题。

这些值来自URL,很遗憾,由于API密钥,我无法提供这些值,但是下面提供了示例结果,但是我目前仅对Name Value感兴趣:

[{"contentType":"SocialWeb","createDate":"2018-04-12 14:07:07","description":"Test Query 1","displayImgUrl":"","editDate":"2018-05-25 13:21:09","fhTwitterStatus":"OFF","fromDate":null,"languageFilters":["English"],"name":"Query1","sharing":"PUBLIC","status":"Active","timeInterval":"LAST_SIX_MONTHS","toDate":null,"topicId":"948015"},
{"contentType":"SocialWeb","createDate":"2017-09-29 10:53:21","description":"Test Query 2","displayImgUrl":"","editDate":"2017-10-18 03:06:41","fhTwitterStatus":"OFF","fromDate":"2017-06-18 02:25:13","languageFilters":["English"],"name":"Query2","sharing":"PUBLIC","status":"Standby","timeInterval":"OPEN_END","toDate":null,"topicId":"845703"},
{"contentType":"SocialWeb","createDate":"2016-11-24 00:53:50","description":"Test Query 3","displayImgUrl":"","editDate":"2016-11-24 00:54:31","fhTwitterStatus":"OFF","fromDate":"2016-11-01 00:00:00","languageFilters":["English"],"name":"Query3","sharing":"PUBLIC","status":"Standby","timeInterval":"OPEN_END","toDate":null,"topicId":"689969"},]

任何帮助将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试使用Microsoft Newtonsoft.Json 像

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

然后您简单地写

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;

电影是类,它包含json中的所有键