[英]How to Convert a String returned from JSON to Object Dot Notation In C# & JSON.Net
我正在使用C#和JSON.Net讀取此JSON文檔:
{
"myValue": "foo.bar.baz"
}
我的目標是使用字符串值“ foo.bar.baz”作為對象點表示法來訪問foo對象中的foo.bar.baz值:
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";
}
}
假設您有一個帶有名為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
種類NullReferenceException
因此您必須對此進行防御性編碼。 但是,這對您來說應該是一個好的開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.