【发布时间】:2011-09-21 16:09:23
【问题描述】:
是否可以使用 JsonProperty 注释将嵌套的 Json 属性映射到非嵌套的 .NET 成员?假设你有一些这样的 Json:
{
"id":9999,
"created_date":"Thu, 23 Jun 2011 12:56:24 +0000",
"pos":{
"type":"someType",
"coordinates":[
59.323,
18.0654
]
}
}
并希望将其反序列化为扁平类 MyClass 使用
JsonConvert.DeserializeObject<MyClass>(jsonstr);
下面的类中是否可以使用注解将Json坐标列表映射到Lat和Lng:
public class MyClass {
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("created_date")]
public DateTime Created { get; set; }
[JsonProperty("????")]
public float Lat { get; set; }
[JsonProperty("?????")]
public float Lng { get; set; }
}
只是好奇。我总是可以像这样定义类,它似乎工作正常:
public class MyClass {
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("date_created")]
public DateTime Created { get; set; }
[JsonProperty("pos")]
public PosClass Pos { get; set; }
}
public class PosClass
{
public List<float> coordinates { get; set; }
}
【问题讨论】:
-
为什么要将其反序列化为扁平化类?
-
这只是一个示例,但显然在很多情况下,您希望对内部数据进行不同于原始 json 表示的建模。