2013-12-23 33 views
1

我使用C#和JSON.Net閱讀本文件的JSON字符串:如何轉換JSON返回到目標點符號在C#&JSON.Net

{ 
    "myValue": "foo.bar.baz" 
} 

我的目標是要使用的字符串值「foo.bar.baz」爲目標點符號訪問foo.bar.baz的價值在Foo對象:

public Foo foo = new Foo(); 

var client = new WebClient(); 
client.Headers.Add("User-Agent", "Nobody"); 
var json = client.DownloadString(new Uri("http://www.example.com/myjson.json")); 
JObject o = JObject.Parse(json); 

foreach (JProperty prop in o.Children<JProperty>()){ 

    Response.Write(????); // should write "Hello World!" 

} 

僅供參考,這裏是Foo類:

public class Foo { 
     public Foo() { 
     this.bar = new Foo(); 
     this.bar.baz = "Hello World"; 
    } 
} 

回答

1

假設您有一個名爲foo的屬性的對象,您可以使用反射來查找您正在查找的值。這將適用於領域,但不這樣做,而是使用公共屬性。

public class SomeContainer 
{ 
    public Foo foo { get; set; } 
} 

var container = new SomeContainer(); 

var myValuePath = "foo.bar.baz"; // Get this from the json 

string[] propertyNames = myValuePath.Split('.'); 

object instance = container; 
foreach (string propertyName in propertyNames) 
{ 
    var instanceType = instance.GetType(); 

    // Get the property info 
    var property = instanceType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); 

    // Get the value using the property info. 'null' is passed instead of an indexer 
    instance = property.GetValue(instance, null); 
} 

// instance will be baz after this loop 

有各種潛在NullReferenceException的,所以你必須防守代碼於此。但是,這對你來說應該是一個好的開始。

+0

謝謝,這是有效的。正如你所提到的,那裏有各種潛在的NullReferenceExceptions。做我所要求的是不是一個好主意?看起來很複雜。 – edt

+0

我不知道你在努力完成什麼......但是,如果明智地使用它並不是最糟糕的想法。您必須信任JSON的供應,否則您放棄訪問您的應用內部。像這樣使用反射速度不是很快,所以不要在關鍵路徑上做數百萬次。 –