如何解决不规则的Json内容
现在我正在解决问题,我从未遇到过。 我的模型中有一个带有此类的ASP.Net rest API:
public class Filter<T> where T : class
{
[JsonProperty(PropertyName = "property1",Required = Required.Always)]
public string Property1 { get; set; }
[JsonProperty(PropertyName = "property2",Required = Required.Always)]
public string Property2 { get; set; } = null;
[JsonProperty(PropertyName = "property3",Required = Required.Always)]
public string Property3 { get; set; }
但是,客户端需要通过以下调用之一将我发送给我:
"filter": [
{
"property1": "xxxx","property2": "xxxx","property3": "xxxx"
},{
"property1": "xxxx","property2": ["xxxx","yyyy"],"property3": "xxxx"
}
],
问题是属性2,该属性一次为字符串,另一次为数组。我该如何处理这类问题? 客户不会让步。财产总是被命名为财产2。
解决方法
您可以为此使用JsonConverter
。转换器将检查它是否是数组,如果是,则返回它。如果没有创建,则将唯一的值添加为该数组中的第一个对象。
internal class MyConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(List<T>));
}
public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer)
{
JToken jtoken = JToken.Load(reader);
if (jtoken.Type == JTokenType.Array)
{
return jtoken.ToObject<List<T>>();
}
else
{
return new List<T> { jtoken.ToObject<T>() };
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然后将Property2
更改为List<string>
,并将Converter作为属性添加。
[JsonConverter(typeof(MyConverter<string>))]
[JsonProperty(PropertyName = "property2",Required = Required.Always)]
public List<string> Property2 { get; set; }
测试
string json_with_array = "[ { \"property1\": \"xxxx\",\"property2\": \"xxxx\",\"property3\": \"xxxx\" },{ \"property1\": \"xxxx\",\"property2\": [\"xxxx\",\"yyyy\"],\"property3\": \"xxxx\" } ]";
string json_without_array = "[ { \"property1\": \"xxxx\",\"property2\": \"zzzz\",\"property3\": \"xxxx\" } ]";
List<TestClass> list1 = JsonConvert.DeserializeObject<List<TestClass>>(json_with_array);
List<TestClass> list2 = JsonConvert.DeserializeObject<List<TestClass>>(json_without_array);
List<TestClass> merged_list = list1.Concat(list2).ToList();
string merged_json = JsonConvert.SerializeObject(merged_list);
结果
[
{
"property1": "xxxx","property2": [
"xxxx"
],"property3": "xxxx"
},{
"property1": "xxxx","property2": [
"xxxx","yyyy"
],"property2": [
"zzzz"
],"property3": "xxxx"
}
]
,
您可以在JSON调用和Filter类之间建立某种介体类,在其中您将检查属性类型,而不是立即对其进行映射。
然后,将Property2的类型更改为数组而不是字符串,并在使用类时检查属性的长度,以检查它是单个字符串还是数组。
编辑:假设您的数组是字符串数组。如果没有,请对像object这样的通用类进行相同的操作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。