我正在编写客户端应用程序,它应该处理服务器响应。回复是JSON。我决定使用Json.NET来反序列化它们。我无法简化或修改这些响应(在服务器端)。这种特定JSON响应的特殊困难是不同的对象类型在同一个数组中:散列和文件数组。所以,我想直接将这个数组反序列化为强类型对象,而不是对象数组。我认为应该可以用CustomCreationConverter
来实现,但我无法想象如何。
JSON:
{
"files":
[
"hash string",
[
["first file name", 12],
["second file name", 34]
]
]
}
我想要实现的对象结构:
public class RootObject
{
[JsonProperty("files")]
public FilesContainer Container
{
get;
set;
}
}
public class FilesContainer
{
public string Hash
{
get;
set;
}
public File[] Files
{
get;
set;
}
}
[JsonConverter(typeof(FileJsonConverter))]
public class File
{
public string Name
{
get;
set;
}
public int Size
{
get;
set;
}
}
class FileJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
File obj = new File
{
Name = reader.ReadAsString(),
Size = reader.ReadAsInt32().GetValueOrDefault()
};
reader.Read();
return obj;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
答案 0 :(得分:5)
我终于想出了如何做到这一点。我需要在serializer.Deserialize
内使用JsonConverter
。所以,这是一个有效的例子。
class Program
{
static string json = @"{
""files"":
[
""hash string"",
[
[""first file name"", 12],
[""second file name"", 34]
]
]
}";
static void Main(string[] args)
{
RootObject container = JsonConvert.DeserializeObject<RootObject>(json);
}
}
public class RootObject
{
[JsonProperty("files")]
public FilesContainer Container
{
get;
set;
}
}
[JsonConverter(typeof(FilesContainerJsonConverter))]
public class FilesContainer
{
public string Hash
{
get;
set;
}
public File[] Files
{
get;
set;
}
}
public class FilesContainerJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
FilesContainer obj = new FilesContainer();
obj.Hash = reader.ReadAsString();
reader.Read(); // to StartArray
obj.Files = serializer.Deserialize<File[]>(reader);
reader.Read(); // to EndArray
return obj;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
[JsonConverter(typeof(FileJsonConverter))]
public class File
{
public string Name
{
get;
set;
}
public int Size
{
get;
set;
}
}
class FileJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
File obj = new File
{
Name = reader.ReadAsString(),
Size = reader.ReadAsInt32().GetValueOrDefault()
};
reader.Read(); // to EndArray
return obj;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}