我正在查询Firebase并检索一组对象,如下所示:
{"-K5f0ccEKkVkxTAavQKY": { "Appeal": { "ID": "1450273330435", "comps": [ 162248, 162272, 162273, 162281, 162544 ], "property": { "Address": "15 Main Street", "propID": 169729 }, "timeDateStamp": "Wed Dec 16 2015 08:42:10 GMT-0500 (Eastern Standard Time)", "userUUID": "google:229139952703238437512", "year": 2016 } }}
我想用这个定义将它们反序列化为对象:
public class Appeal { public string ID; public Listcomps; public AppealProperty property; public string timeDateStamp; public string UUID; public int year; } public class AppealProperty { public string address; public string propID; }
我有麻烦让它反序列化.我不需要初始字符串(例如"K5f0ccEKkVkxTAavQKY"
).如果需要,我可以更改对象定义.我有一种感觉,字典会很有用.
快速而肮脏的对象是Dictionary
用作反序列化目标。到那时,它会很简单:
var firebaseLookup = JsonConvert.DeserializeObject>(json); var data = firebaseLookup.Values.ToList(); // or FirstOrDefault();
如果您必须一次获取多个对象,这种方法也可以处理这种情况,并且如果发现密钥毕竟很重要,它将为您提供使用该密钥的机会。
您可以将数据序列化到下面的类中.
public class AppealProperty { public string Address { get; set; } public int propID { get; set; } } public class Appeal { public string ID { get; set; } public Listcomps { get; set; } public AppealProperty property { get; set; } public string timeDateStamp { get; set; } public string userUUID { get; set; } public int year { get; set; } } public class FireBase { public Appeal Appeal { get; set; } } public class RootObject { [JsonProperty(PropertyName = " - K5f0ccEKkVkxTAavQKY")] public FireBase FireBaseRoot { get; set; } }
假设您正在使用JSON.NET,那么您可以使用以下代码获取您所关注的对象:
var firebaseObject = JsonConvert.DeserializeObject(json); var data = firebaseObject.FireBaseRoot.Appeal;
如果根名称是动态的,如您的注释所示,您可以跳过根目录并直接序列化到FireBase类:
JObject parsedJson = JObject.Parse(json); var fireBase = parsedJson.First.Children().First().ToObject(typeof (FireBase));