这可以通过自定义JsonConverter
.
假设您的课程设置如下:
public class RootObject
{
[JsonProperty("data")]
[JsonConverter(typeof(TeamListConverter))]
public List<Team> Teams { get; set; }
}
public class Team
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
然后您可以使用它JsonConverter
来处理 JSON 数组的反序列化。这将忽略数组中的所有纯字符串(日期),只尝试反序列化对象。
public class TeamListConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(List<Team>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray array = JArray.Load(reader);
List<Team> teams = new List<Team>();
foreach (JToken token in array.Children())
{
if (token.Type == JTokenType.Object)
{
teams.Add(token.ToObject<Team>());
}
}
return teams;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
这是演示程序:
public class Program
{
public static void Main(string[] args)
{
string json = @"
{
""data"":
[
""Monday 13 january"",
{
""id"":""1234aa"",
""name"":""teamA""
},
{
""id"":""1234bb"",
""name"":""teamB""
},
""Tuesday 14 january"",
{
""id"":""1234aa"",
""name"":""teamA""
}
]
}";
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Team t in obj.Teams)
{
Console.WriteLine(t.Id + " - " + t.Name);
}
}
}
这是输出:
1234aa - teamA
1234bb - teamB
1234aa - teamA
这是你想要的?