C# 如何将子对象从JArray获取到ObservableCollection
我正在为Windows Phone开发一个应用程序,其中一个列表框显示JSON文件中的数据。我使用的是C# 如何将子对象从JArray获取到ObservableCollection,c#,json,windows-phone-8,json.net,C#,Json,Windows Phone 8,Json.net,我正在为Windows Phone开发一个应用程序,其中一个列表框显示JSON文件中的数据。我使用的是JArray,可以根据数组位置显示数据。但是如果我想显示JSON文件中的所有数据(该文件没有静态数据,数据可能会在以后修改),该怎么办 我的JSON: [ { "xId": "52", "result": { "type": "Basico.Bean.MunicipioClass.TMunicipio", "
JArray
,可以根据数组位置显示数据。但是如果我想显示JSON文件中的所有数据(该文件没有静态数据,数据可能会在以后修改),该怎么办
我的JSON:
[
{
"xId": "52",
"result": {
"type": "Basico.Bean.MunicipioClass.TMunicipio",
"id": 1,
"fields": {
"FRefCount": 0,
"FId": 52,
"FNome": "Sumare",
"FEstado": "SP",
"FPais": "Brasil"
}
}
},
{
"xId": "52",
"result": {
"type": "Basico.Bean.MunicipioClass.TMunicipio",
"id": 1,
"fields": {
"FRefCount": 0,
"FId": 52,
"FNome": "Indaiatuba",
"FEstado": "SP",
"FPais": "Brasil"
}
}
}
]
我的代码:
InitializeComponent();
String text;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream("json.html", FileMode.Open, FileAccess.Read, FileShare.Read, store))
using (var reader = new StreamReader(readStream))
{
text = reader.ReadToEnd();
}
{
try
{
DataContext = this;
// Your JSON string
string json = text;
// Parse as JObject
JArray jObj = JArray.Parse(json);
// Extract what you need, the "fields" property
JToken jToken = jObj[0]["result"]["fields"];
// Convert as Fields class instance
Fields fields = jToken.ToObject<Fields>();
Items = new ObservableCollection<Fields>() { fields };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public ObservableCollection<Fields> Items { get; set; }
public class Fields
{
[JsonProperty(PropertyName = "FId")]
public int FId { get; set; }
public string FNome { get; set; }
public string FEstado { get; set; }
public string FPais { get; set; }
}
当我使用“[1]”时,返回值为Indaiatuba SP
:
JToken jToken = jObj[0]["result"]["fields"];
JToken jToken = jObj[1]["result"]["fields"];
我需要这样:
Sumare SP
Indaiatuba SP
如果我正确理解了您的问题,那么您正在尝试将JSON中的所有“字段”对象放入您的ObservableCollection
。以下是如何做到这一点:
JArray jObj = JArray.Parse(json);
Items = new ObservableCollection<Fields>(
jObj.Children().Select(jo => jo["result"]["fields"].ToObject<Fields>()));
JArray jObj=JArray.Parse(json);
Items=新的ObservableCollection(
jObj.Children();
如果我正确理解了您的问题,那么您正在尝试将JSON中的所有“字段”对象放入您的
ObservableCollection
。以下是如何做到这一点:
JArray jObj = JArray.Parse(json);
Items = new ObservableCollection<Fields>(
jObj.Children().Select(jo => jo["result"]["fields"].ToObject<Fields>()));
JArray jObj=JArray.Parse(json);
Items=新的ObservableCollection(
jObj.Children();
非常感谢!你救了我一天:)非常感谢!你救了我一天:)