我试图将json字符串反序列化为复杂对象但没有成功:
这是我试图反序列化的类:
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"}
但我一直收到上述错误,这种方式出了什么问题?
答案 0 :(得分:4)
JSON明确表示它是一个字符串,而不是一个数组;
"PostEventsModels":[{"Id":23,...
应该是:
byte[] fileBytes = Convert.FromBase64String(doc.ChildNodes[1].InnerText);
string filePath = LOGPATH + envelopeId.InnerText + "_" + documentId + "_" + documentName + ".pdf";
System.IO.File.WriteAllBytes(filePath , fileBytes);
修复源JSON
答案 1 :(得分:4)
如果格式化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
成为一个字符串,然后再反序列化这个字符串。