Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.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
使用.Net NewtonSoft从json响应中提取key:values数据_.net_Json_Parsing_Json.net_Deserialization - Fatal编程技术网

使用.Net NewtonSoft从json响应中提取key:values数据

使用.Net NewtonSoft从json响应中提取key:values数据,.net,json,parsing,json.net,deserialization,.net,Json,Parsing,Json.net,Deserialization,我有一个小json文件要解析: { "audio_file": { "__type": "File", "name": "somename.m4a", "url": "the_url" }, "createdAt": "2015-07-30T19:37:14.916Z", "location": "Somewhere", "objectId": "CSHgwDuhg8", "updatedAt": "

我有一个小json文件要解析:

{
    "audio_file": {
        "__type": "File",
        "name": "somename.m4a",
        "url": "the_url"
    },
    "createdAt": "2015-07-30T19:37:14.916Z",
    "location": "Somewhere",
    "objectId": "CSHgwDuhg8",
    "updatedAt": "2015-07-30T19:37:14.916Z"
}
我想要一种根据键访问这里所有值的方法。但由于某种原因,我就是做不到

我正在尝试以下方法:

var json = JObject.Parse(rawJson);  
string sjson = json.ToString();

JsonTextReader reader = new JsonTextReader(new StringReader(sjson));
while (reader.Read())
{
    if (reader.Value != null)
        Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
    else
        Console.WriteLine("Token: {0}", reader.TokenType);
};

干杯

序列化是将对象转换为可以存储、在系统之间传递并在需要时转换回对象的形式的过程。表单可以是二进制数据或文本/字符串(例如,音频文件对象的字符串表示)。在和中阅读有关序列化的内容

反序列化是从序列化的二进制/字符串数据中恢复对象的反向过程。在这里学习和。当您执行
JsonConvert.DeserializeObject
时,您已经在使用它了

现在要反序列化已有的数据,需要与数据匹配的类表示。如果你已经有了它,那就好了,否则你需要创建它

您还可以反序列化到
字典
,并用键查找值,但是,这是有风险的,因为您不会进行任何编译时类型检查,如果代码或数据有问题,它将引发运行时异常

让我向您展示一些代码示例

json反序列化代码

你需要的课程

public class AudioFileDetails
{
    public DateTime CreatedAt { get; set;}
    public string Location { get; set; }
    public string Objectid { get; set; }
    public DateTime UpdatedAt { get; set; }
    public FileDetails Audio_File { get; set; }
}

public class FileDetails
{
    public string __Type { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
}
方法使用Newtonsoft.Json进行反序列化

using Newtonsoft.Json.JsonConvert; //Add Json.NET NuGet package

public class JsonSerializer 
{
    public static T DeserializeData<T>(string jsonData)
    {
        try
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonData);
        }
        catch(Exception ex)
        {
            //log exception if required
            return default(T);
        }
    } 
}
使用Newtonsoft.Json.JsonConvert//添加Json.NET NuGet包
公共类JsonSerializer
{
公共静态T反序列化数据(字符串jsonData)
{
尝试
{
返回Newtonsoft.Json.JsonConvert.DeserializeObject(jsonData);
}
捕获(例外情况除外)
{
//日志异常(如果需要)
返回默认值(T);
}
} 
}
现在只需几行代码即可反序列化数据并使用内部值

var jsonString = @"{'audio_file':{'__type':'File','name':'somename.m4a','url':'the_url'},'createdAt':'2015-07-30T19:37:14.916Z','location':'Somewhere','objectId':'CSHgwDuhg8','updatedAt':'2015-07-30T19:37:14.916Z'}";
var data = JsonSerializer.DeserializeData<AudioFileDetails>(jsonString);
var url = data.Audio_File.Url; //access any property here
var jsonString=@“{'audio_file':{'uuu type':'file','name':'somename.m4a','url':'the_url','createdAt':'2015-07-30T19:37:14.916Z','location':'Somewhere','objectId':'CSHgwDuhg8','updatedAt':'2015-07-30T19:37:14.916Z'”;
var data=JsonSerializer.DeserializeData(jsonString);
var url=data.Audio_File.url//在这里访问任何财产
反序列化为字符串、动态字典的代码

var jsonString = @"{'audio_file':{'__type':'File','name':'somename.m4a','url':'the_url'},'createdAt':'2015-07-30T19:37:14.916Z','location':'Somewhere','objectId':'CSHgwDuhg8','updatedAt':'2015-07-30T19:37:14.916Z'}";
var dictionary = JsonSerializer.DeserializeData<Dictionary<string, dynamic>>(jsonString);
//To use, get property with the key. For complex objects, use .PropertyName
var url = dictionary["audio_file"].url; 
var jsonString=@“{'audio_file':{'uuu type':'file','name':'somename.m4a','url':'the_url','createdAt':'2015-07-30T19:37:14.916Z','location':'Somewhere','objectId':'CSHgwDuhg8','updatedAt':'2015-07-30T19:37:14.916Z'”;
var dictionary=JsonSerializer.DeserializeData(jsonString);
//要使用,请使用键获取属性。对于复杂对象,请使用.PropertyName
var url=字典[“音频文件”].url;

同样,编译器不会在编译时检查动态。若有任何错误,它将在运行时抛出异常失败

实际上,您已经反序列化了,并且通过这一行
var json=JObject.Parse(rawJson)获得了所需的一切

这里有一个方法,您可以调用它来获取所需的所有数据

    static void OutputJObject(JObject jsonObject, string indent = "")
    {
        foreach (KeyValuePair<string, JToken> node in jsonObject)
        {
            Console.Write(indent);
            if (node.Value.Type == JTokenType.Object)
            {
                Console.WriteLine("Key: {0}", node.Key);
                OutputJObject((JObject)node.Value, indent + "  ");
            }
            else
            {
                Console.WriteLine("Key: {0}, Value: {1}, Type: {2}", node.Key, node.Value, node.Value.Type);
            }
        }          
    }

这将提供您想要的,而无需处理多个额外的反序列化调用和处理动态。您还可以获得有关值的数据类型的信息。

您有要反序列化的类吗?这是什么意思?我不确定我是否理解反序列化的概念:),所以我这样做了:var jsonResult=JsonConvert.DeserializeObject(sjson);我得到了5个键和它们的值,但我如何才能访问其中一个?例如,URL?嗯……好的,让我们写下答案。给我5分钟。@PavelZagalsky修复了两个拼写错误,请使用此更新代码。此外,我还添加了关于如何使用(但不推荐)词典的说明。哈!明亮的非常感谢你!
Key: audio_file
  Key: __type, Value: File, Type: String
  Key: name, Value: somename.m4a, Type: String
  Key: url, Value: the_url, Type: String
Key: createdAt, Value: 7/30/2015 19:37:14, Type: Date
Key: location, Value: Somewhere, Type: String
Key: objectId, Value: CSHgwDuhg8, Type: String
Key: updatedAt, Value: 7/30/2015 19:37:14, Type: Date