我正在为 Windows Phone 开发一个应用程序,其中的 ListBox 显示来自 JSON 文件的数据。我使用的是 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; }
}
当我使用“[0]”时,返回的是 Sumare SP
:
JToken jToken = jObj[0]["result"]["fields"];
当我使用“[1]”时,返回的是 Indaiatuba SP
:
JToken jToken = jObj[1]["result"]["fields"];
我需要这样的:
Sumare SP
因达亚图巴 SP
最佳答案
如果我正确理解你的问题,你正试图从 JSON 中获取所有“字段”对象到你的 ObservableCollection<Fields>
中。 .以下是您可以如何做到这一点:
JArray jObj = JArray.Parse(json);
Items = new ObservableCollection<Fields>(
jObj.Children().Select(jo => jo["result"]["fields"].ToObject<Fields>()));
关于c# - 如何从 JArray 获取子对象到 ObservableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25266694/