【发布时间】:2014-08-11 19:24:23
【问题描述】:
我正在为 Windows Phone 开发一个应用程序,其中 ListBox 显示来自 Json 文件的数据。 当我的 Json 文件有一项时,我的代码可以正常工作,但是当我的 Json 文件有一项时,异常是
"从 JsonReader 读取 JObject 时出错。当前 JsonReader 项不是 对象:StartArray。路径“,line1,位置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!");
}
}
【问题讨论】:
标签: c# json exception windows-phone-8