如何将返回字符串数组的API响应反序列化为单个C#对象?
解决方法
你遇到的问题核心是JSON根节点是数组,但你要映射到带集合属性的对象,默认序列化器会因为结构不匹配报错,下面分两种常用序列化库给出具体实现:
前提:定义目标类
先确认你的目标类结构(假设属性名为Items,可根据实际调整):
public class StringCollectionDto { public List<string> Items { get; set; } }
方案1:先反序列化为数组,再手动封装对象(最简单)
这种方法不需要自定义转换器,适合快速实现:
使用 Newtonsoft.Json(Json.NET)
string apiResponse = "[\"test\",\"test2\",\"test3\"]"; // 先把JSON数组反序列化为List<string> var stringList = JsonConvert.DeserializeObject<List<string>>(apiResponse); // 手动封装到目标对象 var result = new StringCollectionDto { Items = stringList };
使用 System.Text.Json(.NET Core/.NET 5+ 内置)
string apiResponse = "[\"test\",\"test2\",\"test3\"]"; var stringList = JsonSerializer.Deserialize<List<string>>(apiResponse); var result = new StringCollectionDto { Items = stringList };
方案2:自定义JSON转换器(适合需全局复用的场景)
如果需要在多个地方直接反序列化为目标对象,可以写一个自定义转换器,让序列化器自动处理数组到对象的映射:
Newtonsoft.Json 转换器实现
public class StringCollectionDtoConverter : JsonConverter<StringCollectionDto> { public override StringCollectionDto ReadJson(JsonReader reader, Type objectType, StringCollectionDto existingValue, bool hasExistingValue, JsonSerializer serializer) { // 读取数组并转换为List<string> var list = serializer.Deserialize<List<string>>(reader); return new StringCollectionDto { Items = list }; } public override void WriteJson(JsonWriter writer, StringCollectionDto value, JsonSerializer serializer) { // 如果需要序列化对象回数组,这里也做对应处理 serializer.Serialize(writer, value.Items); } } // 使用转换器 string apiResponse = "[\"test\",\"test2\",\"test3\"]"; var result = JsonConvert.DeserializeObject<StringCollectionDto>(apiResponse, new StringCollectionDtoConverter());
System.Text.Json 转换器实现
public class StringCollectionDtoConverter : JsonConverter<StringCollectionDto> { public override StringCollectionDto Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var list = JsonSerializer.Deserialize<List<string>>(ref reader, options); return new StringCollectionDto { Items = list }; } public override void Write(Utf8JsonWriter writer, StringCollectionDto value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value.Items, options); } } // 使用转换器 string apiResponse = "[\"test\",\"test2\",\"test3\"]"; var options = new JsonSerializerOptions(); options.Converters.Add(new StringCollectionDtoConverter()); var result = JsonSerializer.Deserialize<StringCollectionDto>(apiResponse, options);
为什么之前的普通类反序列化失败?
默认情况下,序列化器期望JSON根节点是与类结构匹配的对象(比如{"Items": ["test","test2","test3"]}),但你的API返回的是数组,结构不匹配,所以直接反序列化会抛出格式错误。上面的两种方案都是通过“先转数组再封装”或者“自定义转换器适配结构”来解决这个问题。
内容的提问来源于stack exchange,提问作者Optional
相关产品推荐
相关产品推荐

