2016-03-09 71 views
1

我有一個有很多成員的類,我可以通過使用JSON.net將JSON反序列化到它中直接創建一個實例。如何將JSON文件直接映射到當前實例?

如何才能達到與我班的當前實例相同的結果?

class Person { 
    public string Name; 
    public int Age; 
    public string[] NickNames; 

    public Person(){} 

    public void LoadInfo(string textFile){ 
     Person p = this; 
     p = JsonConvert.DeserializeObject<Person>(textFile); 

     // I want to do something like: this = p; 
     // but I can't since this operator is read-only 
    } 
} 
+0

只是想確定,你是否試圖將屬性和值從json映射到這個類? – KrishnaDhungana

+0

不能分配',因爲它是隻讀的[this = p isbebeden] – Coding4Fun

+0

@KrishnaDhungana是的,json文件存儲屬性的值,我希望它們被加載到當前實例。 –

回答

4

我認爲你正在尋找的JsonConvert.PopulateObject:

class Person { 
    public string Name; 
    public int Age; 
    public string[] NickNames; 

    public Person(){} 

    public void LoadInfo(string textFile){ 
     JsonConvert.PopulateObject(textFile, this); 
    } 
} 

底線:如果它是關於JSON,Json.Net夠了!

+0

我知道那裏會有這樣的方法!感謝您指出。 –

0

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)); 
      } 

    } 
} 
+0

因此,基本上JSON的容器類必須是獨立的類?我曾考慮過這種方法,但我想檢查是否有人知道直接方法。但這仍然是一個有效的答案。 –

+0

我不知道如何直接從類實例中映射,我可以將其視爲LoadInfo()的一部分創建Person的新實例,然後使用反射將屬性映射回當前實例'。但是這似乎比擁有包裝更復雜。 – JanR

+0

使用'reflection'將我的答案更新爲自動將屬性映射回實例。 – JanR

0

您不能分配到this,因爲它是一個參考,它不允許重新分配自己的參考。所以,如果你想映射屬性或創建新的聯繫人,然後我想在這裏提出一些選項:

  1. 地圖手動性能

這意味着你得到deserialised對象之後,地圖像新的一樣的人: this.Name = p.Name等..

  • 等工具Automapper
  • 自動地圖每個是對象映射器的對象。 https://github.com/AutoMapper/AutoMapper/wiki/Getting-started

    OR

    創建一個包裝類等@JanR或使用創建從解序列化對象的人的靜態方法。

    我希望這會有所幫助。