C# JavaScriptSerializer.Deserialize, возвращающий ноль - PullRequest
0 голосов
/ 21 апреля 2020

Пытается десериализовать строку JSON, я просто получаю null , возвращенный из сериализатора.

JSON действительно, я проверил.

Мои глаза потрясенно смотрят на это сейчас, так что теперь я так надеюсь, что кто-то с большим опытом работы с сериализатором, чем я, сможет заметить что-то «очевидное»!?

Спасибо за любые советы :)

RootObject[] jsonResponse = null;
try
{
    if (httpWResp.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = httpWResp.GetResponseStream();
        string jsonString = null;
        using (StreamReader reader = new StreamReader(responseStream))
        {
            jsonString = reader.ReadToEnd().Replace("\\", "");
            reader.Close();
        }
        JavaScriptSerializer sr = new JavaScriptSerializer();
        jsonResponse = sr.Deserialize<RootObject[]>(jsonString);

Json - это:

{
    "Tags":[
        {
            "Name":"Requestable",
            "TotalOccurrences":1,
            "SizePercentage":0.33333333333333331
        },
        {"Name":"Generic","TotalOccurrences":1,"SizePercentage":0.33333333333333331},
        {"Name":"YYYYYYY","TotalOccurrences":1,"SizePercentage":0.33333333333333331}
    ],
    "Data":[
        {
            "LogonName":"xxxxxxxxxxxxxx",
            "NetBiosName":"YYYYYYY",
            "FriendlyName":"xxxxxxxx",
            "Description":"xxxxxxxxxx",
            "GroupTypeName":"zzzzzzzzz",
            "AllowJoinRequests":true,
            "RiskFactorTotal":null,
            "IsHighSecurityGroup":false,
            "Email":null,
            "DistinguishedName":"xxx,yyy,xxx",
            "ResourceID":12345,
            "GroupID":6789,
            "ValidUntil":null,
            "IsMailEnabled":false,
            "Notes":null,
            "RiskFactorLastCalculated":null
        }
    ],
    "OutParameters":[
        {"Name":"totalCount","Value":1}
    ]
}

И мои занятия такие:

    public class RootObject
    {
        public List<Tag> Tags { get; set; }
        public List<Datum> Data { get; set; }
        public List<OutParameter> OutParameters { get; set; }
    }
    public class Tag
    {
        public string Name { get; set; }
        public int TotalOccurrences { get; set; }
        public double SizePercentage { get; set; }
    }

    public class Datum
    {
        public string LogonName { get; set; }
        public string NetBiosName { get; set; }
        public string FriendlyName { get; set; }
        public string Description { get; set; }
        public string GroupTypeName { get; set; }
        public string AllowJoinRequests { get; set; }
        public string RiskFactorTotal { get; set; }
        public string IsHighSecurityGroup { get; set; }
        public string Email { get; set; }
        public string DistinguishedName { get; set; }
        public int ResourceID { get; set; }
        public int GroupID { get; set; }
        public string ValidUntil { get; set; }
        public string IsMailEnabled { get; set; }
        public string Notes { get; set; }
        public string RiskFactorLastCalculated { get; set; }
    }

    public class OutParameter
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }

Ответы [ 2 ]

1 голос
/ 21 апреля 2020

Измените свой базовый класс

public class Datum
    {
        public string LogonName { get; set; }
        public string NetBiosName { get; set; }
        public string FriendlyName { get; set; }
        public string Description { get; set; }
        public string GroupTypeName { get; set; }
        public bool AllowJoinRequests { get; set; }
        public string RiskFactorTotal { get; set; }
        public bool IsHighSecurityGroup { get; set; }
        public string Email { get; set; }
        public string DistinguishedName { get; set; }
        public int ResourceID { get; set; }
        public int GroupID { get; set; }
        public string ValidUntil { get; set; }
        public bool IsMailEnabled { get; set; }
        public string Notes { get; set; }
        public string RiskFactorLastCalculated { get; set; }
    }
1 голос
/ 21 апреля 2020

Обратите внимание, что есть 3 bool свойства, которые вы определили как строку: AllowJoinRequests, IsHighSecurityGroup, IsMailEnabled:

public partial class RootObject
{
    [JsonProperty("Tags")]
    public List<Tag> Tags { get; set; }

    [JsonProperty("Data")]
    public List<Datum> Data { get; set; }

    [JsonProperty("OutParameters")]
    public List<OutParameter> OutParameters { get; set; }
}

public partial class Datum
{
    [JsonProperty("LogonName")]
    public string LogonName { get; set; }

    [JsonProperty("NetBiosName")]
    public string NetBiosName { get; set; }

    [JsonProperty("FriendlyName")]
    public string FriendlyName { get; set; }

    [JsonProperty("Description")]
    public string Description { get; set; }

    [JsonProperty("GroupTypeName")]
    public string GroupTypeName { get; set; }

    [JsonProperty("AllowJoinRequests")]
    public bool AllowJoinRequests { get; set; }

    [JsonProperty("RiskFactorTotal")]
    public object RiskFactorTotal { get; set; }

    [JsonProperty("IsHighSecurityGroup")]
    public bool IsHighSecurityGroup { get; set; }

    [JsonProperty("Email")]
    public object Email { get; set; }

    [JsonProperty("DistinguishedName")]
    public string DistinguishedName { get; set; }

    [JsonProperty("ResourceID")]
    public long ResourceID { get; set; }

    [JsonProperty("GroupID")]
    public long GroupID { get; set; }

    [JsonProperty("ValidUntil")]
    public object ValidUntil { get; set; }

    [JsonProperty("IsMailEnabled")]
    public bool IsMailEnabled { get; set; }

    [JsonProperty("Notes")]
    public object Notes { get; set; }

    [JsonProperty("RiskFactorLastCalculated")]
    public object RiskFactorLastCalculated { get; set; }
}

public partial class OutParameter
{
    [JsonProperty("Name")]
    public string Name { get; set; }

    [JsonProperty("Value")]
    public long Value { get; set; }
}

public partial class Tag
{
    [JsonProperty("Name")]
    public string Name { get; set; }

    [JsonProperty("TotalOccurrences")]
    public long TotalOccurrences { get; set; }

    [JsonProperty("SizePercentage")]
    public double SizePercentage { get; set; }
}

Обратите внимание, что для свойств, которые определены как object ниже, вам нужна строка Json, которая на самом деле имеет их.

РЕДАКТИРОВАТЬ: Вторая проблема с вашим кодом заключается в том, что, хотя ваша строка json образца не является массивом, вы пытаетесь десериализовать ее в качестве таких. попробуйте изменить эту строку:

jsonResponse = sr.Deserialize<RootObject[]>(jsonString);

на эту:

jsonResponse = sr.Deserialize<RootObject>(jsonString);
...