Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#&;中将JSON返回的字符串转换为对象点符号;JSON.Net_C#_Asp.net_Json.net - Fatal编程技术网

如何在C#&;中将JSON返回的字符串转换为对象点符号;JSON.Net

如何在C#&;中将JSON返回的字符串转换为对象点符号;JSON.Net,c#,asp.net,json.net,C#,Asp.net,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.DownloadStri

我正在使用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 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。照我说的做是个坏主意吗?看起来很复杂。我不知道你想完成什么。。。然而,如果使用得当,这并不是最糟糕的想法。您必须信任JSON的提供,否则您将放弃对应用程序内部的访问。像这样使用反射并不是很快,所以不要在关键路径中重复数百万次。
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