我正在为Windows Phone开发一个应用程序,其中ListBox显示来自Json文件的数据。 当我的Json文件有一个项目时,我的代码工作正常,但是当更多的时候,例外是
"从JsonReader读取JObject时出错。当前的JsonReader项目不是 object:StartArray。路径",第1行,第1位。"
Json1工作正常时:
{"xId":"52","result":{"type":"Basico.Bean.MunicipioClass.TMunicipio","id":1,"fields":{"FRefCount":0,"FId":52,"FNome":"Sumare","FEstado":"SP","FPais":"Brasil"}}}
Json2工作不好时:
[{"xId":"52","result":{"type":"Basico.Bean.MunicipioClass.TMunicipio","id":1,"fields":{"FRefCount":0,"FId":52,"FNome":"Sumare","FEstado":"SP","FPais":"Brasil"}}},{"xId":"53","result":{"type":"Basico.Bean.MunicipioClass.TMunicipio","id":2,"fields":{"FRefCount":0,"FId":53,"FNome":"Paulinia","FEstado":"SP","FPais":"Brasil"}}}]
我的代码:
public PivotPage1()
{
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
JObject jObj = JObject.Parse(json);
// Extract what you need, the "fields" property
JToken jToken = jObj["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; }
}
private void AddProd(object sender, RoutedEventArgs e)
{
if (ListBoxx.SelectedItem != null)
{
Fields fi = (Fields)this.ListBoxx.SelectedItem;
ListBoxx2.Items.Add(fi);
}
else
{
MessageBox.Show("Selecione um item para adicionar!");
}
}
答案 0 :(得分:0)
您应该将json解析为数组而不是对象。你最好的选择是让json保持一致,即总是有一个集合,即使你只有一个项目。
然后你可以解析你的json:
JArray arr = JArray.Parse(json);
foreach (JObject obj in arr.Children<JObject>())
{
...
}