其实我这样收到Json:
{
"id" : 1,
"items": [
{
"media": {
"id": 1,
}
},
{
"media": {
"id": 2,
},
}
],
"status": "ok"
}
我创建了这样的类来映射实体
public class Message
{
[JsonProperty("items")]
public List<Item> Items { get; set; }
}
public class Item
{
[JsonProperty("media")]
public Media Media { get; set; }
}
public class Media
{
[JsonProperty("id")]
public string Id { get; set; }
}
这项工作完美但我的问题是: 是否可以删除Item类并直接在Media of List中进行转换以简化?
更新 我很确定它是可能的,我发布之前发现的第一种方式是JSonConverter,但我不确定这是最好的方法,我想知道是否有更简单的解决方案,例如属性。
答案 0 :(得分:0)
是,您可以,例如使用(私人)字典
public class Message
{
public List<Media> Items { get; set; }
}
public class Media
{
[JsonProperty("media")]
private Dictionary<string, string> IdDict;
public string Id
{
get { return IdDict["id"]; }
set { IdDict["id"] = value; }
}
}
用法
var result = JsonConvert.DeserializeObject<Message>(json);
var test = result.Items[1].Id;
或者,您可以通过实施转换器
来实现结果 public class MediaConverter : JsonCreationConverter<Message>
{
protected override Message Create(Type objectType, JObject jObject)
{
var msg = new Message();
msg.Items = new List<Media>();
foreach (var item in jObject["items"])
{
Media media = new Media();
media.Id = item["media"]["id"].Value<string>();
msg.Items.Add(media);
}
return msg;
}
}
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
return target;
}
public override void WriteJson(JsonWriter writer,
object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
<强>用法强>
var result = JsonConvert.DeserializeObject<Message>(json, new MediaConverter());
var test = result.Items[1].Id;