Json将字符串转换为Collection [英] JsonConvert string to Collection
问题描述
我从API获得这种json格式:
I get this json format from an API:
"url_service": "",
"Description": null,
"Target": "5,6",
"Category ": "2"
我正在尝试将json反序列化为模型。问题出在目标字段,该字段应该是int的ICollection。
这是我的模型:
I'm trying to deserialize the json into a model. The trouble is with the "Target" field which is supposed to be an ICollection of int. Here is my model:
public string Description{ get; set; }
public ICollection<int> Target{ get; set; }
public int Category { get; set; }
是否有一种方法可以在序列化Json之前对其进行处理,以便从中收集出一个集合逗号分隔的字符串?
Is there a way to process the Json before it gets serialised in order to make a collection out of the comma separated string?
推荐答案
不是尝试更改反序列化逻辑,而是为什么不对其进行简化,而只需在模型中包括一个新属性?
Instead of trying to change the deserialization logic, why not make it easier on yourself and just include a new property in your model?
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();
请注意,我的代码中没有错误处理,因此您必须进行相应的修改。
Be aware that there is no error handling in my code so you will have to modify accordingly.
这篇关于Json将字符串转换为Collection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!