的LoadInfo
方法您試圖類不添加到deserialize
,爲此創建單獨的包裝類。
然後添加正確的屬性。
喜歡的東西:
[DataContract]
public class Person {
[DataMember]
public string Name {get; set;}
[DataMember]
public int Age {get; set;}
[DataMember]
public string[] NickNames {get; set;}
public Person(){}
}
public class PersonController
{
public Person LoadInfo(string textFile){
var p = JsonConvert.DeserializeObject<Person>(textFile);
//return an instance of person, mapped from the textfile.
return p;
}
}
如果你想保留它在實例中,你可以做這樣的事情使用反射:
using System.Reflection;
class Person {
public string Name {get; set;}
public int Age {get; set;}
public string[] NickNames {get; set;}
public Person(){}
public void LoadInfo(string textFile)
{
//assign the values to a new instance.
Person p = new Person();
p = JsonConvert.DeserializeObject<Person>(textFile);
//get all the properties of the person class.
var properties = this.GetType().GetProperties();
//loop through the properties.
foreach (var property in properties)
{
//Get the type (Person)
Type type = this.GetType();
//set the value for the property.
type.GetProperty(property.Name).SetValue(this, type.GetProperty(property.Name).GetValue(p));
}
}
}
只是想確定,你是否試圖將屬性和值從json映射到這個類? – KrishnaDhungana
不能分配',因爲它是隻讀的[this = p isbebeden] –
Coding4Fun
@KrishnaDhungana是的,json文件存儲屬性的值,我希望它們被加載到當前實例。 –