猿问

Json将字符串转换为Collection

我从API获取此json格式:


"url_service": "",

"Description": null,

"Target": "5,6",

"Category ": "2"

我正在尝试将json反序列化为模型。问题出在“目标”字段,该字段应该是int的ICollection。这是我的模型:


public string Description{ get; set; }

public ICollection<int> Target{ get; set; }

public int Category { get; set; }

有没有一种方法可以在序列化Json之前处理Json,以便从逗号分隔的字符串中进行收集?


开心每一天1111
浏览 250回答 3
3回答

翻翻过去那场雪

与其尝试更改反序列化逻辑,不如不让它变得更简单,而仅在模型中包含一个新属性?public string Description{ get; set; }public int Category { get; set; }//Change this back to string, since that is what your JSON ispublic string Target{ get; set; }//Add a "TargetList" property that just reads from "Target" and turns into a Listpublic List<int> TargetList => Target.Split(',').Select(x => int.Parse(x)).ToList();请注意,我的代码中没有错误处理,因此您将必须进行相应的修改。

慕容森

Target字段在json中为字符串类型,因此序列化程序将尝试将其读取为字符串。您可以使用转换器来推翻它,例如使用Newtonsoft Json。假设您的数据结构定义如下:public class Data {&nbsp; &nbsp; public string Description{ get; set; }&nbsp; &nbsp; public ICollection<int> Target{ get; set; }&nbsp; &nbsp; public int Category { get; set; }}然后,您可以创建自己的JsonConverter,如下所示:public class DataConverter : JsonConverter {&nbsp; &nbsp; public override bool CanWrite => false;&nbsp; &nbsp; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {&nbsp; &nbsp; &nbsp; &nbsp; throw new NotImplementedException();&nbsp; &nbsp; }&nbsp; &nbsp; public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {&nbsp; &nbsp; &nbsp; &nbsp; var jObject = JObject.Load(reader);&nbsp; &nbsp; &nbsp; &nbsp; var data = new Data();&nbsp; &nbsp; &nbsp; &nbsp; if (jObject.TryGetValue("Description", out JToken jDescription)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.Description = jDescription.Value<string>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (jObject.TryGetValue("Target", out JToken jTarget)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.Target = ToTarget(jTarget, serializer);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (jObject.TryGetValue("Category", out JToken jCategory)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.Category = jCategory.Value<int>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return req;&nbsp; &nbsp; }&nbsp; &nbsp; private static ICollection<int> ToTarget( JToken jTarget, JsonSerializer serializer ) {&nbsp; &nbsp; &nbsp; &nbsp; int defaultValue = -1;&nbsp; &nbsp; &nbsp; &nbsp; var target = new List<int>();&nbsp; &nbsp; &nbsp; &nbsp; var collection = jTarget.Value<string>().Split(',');&nbsp; &nbsp; &nbsp; &nbsp; foreach (string str in collection)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (int.TryParse(str, out int number))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; target.Add(number);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; target.Add(defaultValue);&nbsp; &nbsp; &nbsp; &nbsp; return target;&nbsp; &nbsp; }&nbsp; &nbsp; 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特定的信息和解析逻辑保持清晰。
随时随地看视频慕课网APP
我要回答