【发布时间】:2020-07-07 17:35:45
【问题描述】:
我正在尝试将联系人的 json 文件解析为列表,并在显示联系人姓名的页面上的选择器中将该列表显示给用户。
我的项目根目录中有一个名为“contacts.json”的 json 文件,它的构建操作设置为嵌入式资源。
我的 contacts.json 文件
{
"contacts": [
{
"name": "JOE",
"email": "name@handle",
"phoneNumber": "123-456-7890"
},
{
"name": "JYM",
"email": "name@handle",
"phoneNumber": "123-456-7890"
}
]
}
我的联系方式:
public partial class RootObject
{
[JsonProperty("contacts")]
public List<Contact> Contacts { get; set; }
}
public partial class Contact
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("phoneNumber")]
public string PhoneNumber { get; set; }
}
我实现 json 解析器的页面视图模型
public partial class Page10 : BaseViewModel
{
private List<Contact> _contacts;
public List<InternalContact> contacts
{
get { return _contacts; }
set
{
_contacts = value;
OnPropertyChanged("contacts");
}
}
public Page10()
{
Title = "Spill Info";
contacts = GetJsonData();
}
private List<Contact> GetJsonData()
{
string jsonFileName = "contacts.json";
RootObject ObjContactList = new RootObject();
var assembly = typeof(Page10).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
using (var reader = new System.IO.StreamReader(stream))
{
var jsonString = reader.ReadToEnd();
//Converting JSON Array Objects into generic list
ObjContactList = JsonConvert.DeserializeObject<RootObject>(jsonString);
}
return ObjContactList.Contacts;
}
}
我的基础视图模型
public class BaseViewModel : INotifyPropertyChanged
{
string title = string.Empty;
public string Title
{
get { return title; }
set { SetProperty(ref title, value); }
}
protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName]string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
我的 page.xaml.cs
public partial class Page10 : ContentPage
{
public Page10()
{
InitializeComponent();
this.BindingContext = new contactviewmodel();
}
}
我的页面 xaml
<ContentPage.Content>
<StackLayout>
<Picker Title="contacts" ItemsSource="{Binding contacts}" ItemDisplayBinding="{Binding Name}"/>
</StackLayout>
</ContentPage.Content>
在尝试上述操作后,我在选择时得到一个空选择器,但我希望在选择器中看到 JOE 和 JYM。
编辑 1: 我设法让它们显示在一个列表中,所以我试图从那里将它们放入选择器,但我只得到我的对象类型而不是名称的列表在选择器中。更新代码以反映更改。 image of phone w/ contact list view and picker(还不能嵌入图片,没有足够的代表)。
edit2:修改代码以显示@Cherry Bu-MSFT 的实现
【问题讨论】:
-
myContactList必须是公共属性 - 即,有一个get;
标签: c# json xamarin.forms data-binding picker