3 回答
TA贡献2065条经验 获得超14个赞
与其尝试更改反序列化逻辑,不如不让它变得更简单,而仅在模型中包含一个新属性?
public string Description{ get; set; }
public int Category { get; set; }
//Change this back to string, since that is what your JSON is
public string Target{ get; set; }
//Add a "TargetList" property that just reads from "Target" and turns into a List
public List<int> TargetList => Target.Split(',').Select(x => int.Parse(x)).ToList();
请注意,我的代码中没有错误处理,因此您将必须进行相应的修改。
TA贡献1853条经验 获得超18个赞
Target字段在json中为字符串类型,因此序列化程序将尝试将其读取为字符串。您可以使用转换器来推翻它,例如使用Newtonsoft Json。
假设您的数据结构定义如下:
public class Data {
public string Description{ get; set; }
public ICollection<int> Target{ get; set; }
public int Category { get; set; }
}
然后,您可以创建自己的JsonConverter,如下所示:
public class DataConverter : JsonConverter {
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
var jObject = JObject.Load(reader);
var data = new Data();
if (jObject.TryGetValue("Description", out JToken jDescription)) {
data.Description = jDescription.Value<string>();
}
if (jObject.TryGetValue("Target", out JToken jTarget)) {
data.Target = ToTarget(jTarget, serializer);
}
if (jObject.TryGetValue("Category", out JToken jCategory)) {
data.Category = jCategory.Value<int>();
}
return req;
}
private static ICollection<int> ToTarget( JToken jTarget, JsonSerializer serializer ) {
int defaultValue = -1;
var target = new List<int>();
var collection = jTarget.Value<string>().Split(',');
foreach (string str in collection)
if (int.TryParse(str, out int number))
target.Add(number);
else
target.Add(defaultValue);
return target;
}
public override bool CanConvert(Type objectType) => objectType == typeof(Data);
}
然后,您可以使用以下代码反序列化:
var jsonSettings = new JsonSerializerSettings();
jsonSettings.Converters.Add(new DataConverter);
Data data = JsonConvert.DeserializeObject<Data>(yourJsonString, jsonSettings);
进一步考虑:这种方法可以使您的数据定义和数据解析逻辑之间清楚地分开,从而使您的数据结构和定义与任何json特定的信息和解析逻辑保持清晰。
- 3 回答
- 0 关注
- 249 浏览
添加回答
举报