简体   繁体   中英

Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1

I am trying to deserializing json string to a complex object with no success:

This is the class I am trying to deserialize to:

public class ExcludePublisherRule : BaseAutomaticRule
{

    public int LineIdx { get; set; }

    [Required]
    [Range(30, 1000)]
    public int MininumInstalls { get; set; }

    [Required]
    public int UsingDataFrom { get; set; }

    [Required]
    public List<PostEventModel> PostEventsModels { get; set; }

}

public abstract class BaseAutomaticRule
{
    public int Id { get; set; }

    [Required(ErrorMessage = "*Rule name is required")]
    [StringLength(70)]
    public string Name { get; set; }

    public DateTime LastActivated { get; set; }

    [Required]
    public string CampaignId { get; set; }

    public int StatusId { get; set; }
}


public class PostEventModel
{
    public int Id { get; set; }
    public int PublisherInstalls { get; set; }
}


This is how I try to do it:
//Get type and Object and returns a class object.
    public T ConvertToAutomaticRule<T>(dynamic automaticRuleJSON)
    {
        var json = "";
        try
        {
            var serializer = new JavaScriptSerializer();
            json = serializer.Serialize(automaticRuleJSON);
            return serializer.Deserialize<T>(json);
        }
        catch (Exception ex)
        {
            log.Error($"Ex message: {ex.Message}, json is {json}");
            return default(T);
        }

    }

The json:

{"automaticRuleName":"asd","installsNumber":"30","usingDataFrom":"1","ruleStatusId":"1","automaticRuleID":"0","PostEventsModels":"[{\"Id\":\"23\",\"PublisherInstalls\":\"15\"},{\"Id\":\"2\",\"PublisherInstalls\":\"96\"}]","campaignId":"95e62b67-ba16-4f76-97e4-dd96f6e951c7"}

But I keep getting the error above, what's wrong with this way?

The JSON explicitly says it is a string, not an array;

"PostEventsModels":"[{\"Id\":\"23\",...

should be:

"PostEventsModels":[{"Id":23,...

Fix the source JSON

If you format your json (for example on https://jsonformatter.curiousconcept.com/ ) you can see that the property PostEventsModels is not a json list, but a string representation of it.

{  
   "automaticRuleName":"asd",
   "installsNumber":"30",
   "usingDataFrom":"1",
   "ruleStatusId":"1",
   "automaticRuleID":"0",
   "PostEventsModels":"[{\"Id\":\"23\",\"PublisherInstalls\":\"15\"},{\"Id\":\"2\",\"PublisherInstalls\":\"96\"}]",
   "campaignId":"95e62b67-ba16-4f76-97e4-dd96f6e951c7"
}

So you need to correct the json generation, or let property PostEventsModels be a string, and then deserialize this string later.

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