2017-05-09 78 views
0

我試圖JSON字符串反序列化到沒有成功一個複雜的對象:無法將類型「System.String」的對象鍵入「System.Collections.Generic.List`1

這是我的班嘗試反序列化到:

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

    } 

的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"} 

但我不斷收到上述錯誤,有什麼不對的呢?

回答

3

如果格式化JSON(例如在https://jsonformatter.curiousconcept.com/),你可以看到屬性PostEventsModels不是一個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" 
} 

所以,你需要糾正json的一代,還是讓財產PostEventsModels是一個字符串,再後來反序列化這個字符串。

3

JSON明確表示它是一個字符串,而不是一個數組;

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

應該是:

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

修復源JSON

相關問題