Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.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# 从C中的JSON对象中获取值#_C#_Json - Fatal编程技术网

C# 从C中的JSON对象中获取值#

C# 从C中的JSON对象中获取值#,c#,json,C#,Json,我有一个JSON结构,如下所示 {"name":"user1","param":{"showid":"test"}} {"name1":"user2","param1":{"showname":"test1"}} 我将把JSON结构的值传递给一个程序,从中提取JSON对象的值。 但是每个JSON对象的键值都不同。 因此,我无法创建JSON对象的结构来检索值 ie:下次JSON对象可能如下所示 {"name":"user1","param":{"showid":"test"}}

我有一个JSON结构,如下所示

  {"name":"user1","param":{"showid":"test"}}
  {"name1":"user2","param1":{"showname":"test1"}}
我将把JSON结构的值传递给一个程序,从中提取JSON对象的值。 但是每个JSON对象的键值都不同。 因此,我无法创建JSON对象的结构来检索值

ie:下次JSON对象可能如下所示

  {"name":"user1","param":{"showid":"test"}}
  {"name1":"user2","param1":{"showname":"test1"}}

如何从c#?

中的JSON结构中迭代键值对,您可以使用System.Web.Script.Serialization.JavaScriptSerializer(System.Web.Extensions.dll)并将其加载到数据类型“dynamic”中,然后您可以像访问字典一样访问属性

或者可以使用反射查找可用的属性/字段,并获取字段/属性的值

public static Dictionary<string, object> ToPropertyDictionary(this object obj)
{
    var dictionary = new Dictionary<string, object>();
    foreach (var propertyInfo in obj.GetType().GetProperties())
        if (propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0)
            dictionary[propertyInfo.Name] = propertyInfo.GetValue(obj, null);
    return dictionary;
}
公共静态字典TopPropertyDictionary(此对象obj)
{
var dictionary=newdictionary();
foreach(obj.GetType().GetProperties()中的var propertyInfo)
if(propertyInfo.CanRead&&propertyInfo.GetIndexParameters().Length==0)
dictionary[propertyInfo.Name]=propertyInfo.GetValue(obj,null);
返回字典;
}

用任何json库解析它?Google Hatchs?JSON结构将用Javascript创建,在另一端,我需要在C#中迭代它,而不使用任何第三方引用。如果不使用第三方引用,您需要阅读JSON规范并编写自己的解析器。但我认为这不是最好的主意,为什么不能使用thirdparty?如果你不打算使用第三方库,那么就使用
DataContractJsonSerializer
或者自己解析它。您不需要知道JSON的结构就可以解析它……我的程序是在.NET3.5中开发的,不支持动态关键字。您能提供一些如何使用反射实现此目的的示例代码吗?公共类JsonDeserializer{private IDictionary jsonData{get;set;}公共静态字典TopPropertyDictionary(此对象obj){var Dictionary=new Dictionary();foreach(obj.GetType().GetProperties()中的var propertyInfo)如果(propertyInfo.CanRead&&propertyInfo.GetIndexParameters().Length==0)字典[propertyInfo.Name]=propertyInfo.GetValue(obj,null);return dictionary;}您能找出这里出错的原因吗?@user833985:obj==null?