简体   繁体   English

如何解析此JSON(使用JSON.NET)?

[英]How do I parse this JSON (using JSON.NET)?

I have some JSON which is valid but a little quirky looking. 我有一些有效的JSON,但看上去有些古怪。 Here it is: 这里是:

{
"server":"some server name",
"files":
{
"filename1":{"source":"original","format":"text"},
"filename2":{"source":"original","format":"text"},
"filename3":{"source":"original","format":"text"}
}
}

As you can see, the "files" section contains one JSON object per "file" so I can get this as array of JTokens but not sure how to get the values of "filename1", "filename2", etc. out. 如您所见,“文件”部分每个“文件”包含一个JSON对象,因此我可以将其作为JTokens数组获取,但不确定如何获取“ filename1”,“ filename2”等值。

I'm using JSON.NET and C# so please don't provide an answer that requires the JavaScriptSerializer from System.Web.Extensions.dll. 我正在使用JSON.NET和C#,所以请不要提供需要System.Web.Extensions.dll中的JavaScriptSerializer的答案。 Either pure JObject/JToken calls or JConvert.DeserializeObject<> would be okay. 纯JObject / JToken调用或JConvert.DeserializeObject <>都可以。

Thanks. 谢谢。

Try this 尝试这个

public class Data
{
    public Data()
    {
        Files = new Dictionary<string, FileData>();
    }
    public string Server { get; set; }
    public IDictionary<string, FileData> Files { get; set; } 
}
public class FileData
{
    public string Source { get; set; }
    public string Format { get; set; }
}

Then Access it using this 然后使用它访问

var result = JsonConvert.DeserializeObject<Data>(JsonValue);

How about using dynamic deserialization? 如何使用动态反序列化? See Deserialize json object into dynamic object using Json.net 请参阅使用Json.net将JSON对象反序列化为动态对象

string json = @"{""server"":""some server name"",""files"":{""filename1"":{""source"":""original"",""format"":""text""},""filename2"":{""source"":""original"",""format"":""text""},""filename3"":{""source"":""original"",""format"":""text""}}}";
dynamic result = JObject.Parse(json);

Console.WriteLine(result.server);
foreach (dynamic file in result.files)
{
    Console.WriteLine(file.Name);
    dynamic value = file.Value;
    Console.WriteLine(value.source);
    Console.WriteLine(value.format);
}

Output 输出量

some server name
filename1
original
text
filename2
original
text
filename3
original
text

You must define a class like this: 您必须定义一个这样的类:

class ClassName
{
    public string server;
    public ClassName2 files;
}

and define ClassName2: 并定义ClassName2:

class ClassName2
{
    ClassName3 filename1;
    ClassName3 filename2;
    ClassName3 filename3;
}

and finally ClassName3 最后是ClassName3

ClassName3
{
    public string source;
    public string format;
}

supporse you have saved your json data in a string variable like 'result' 支持您已将json数据保存在字符串变量(如“结果”)中

 ClassName fin = JsonConvert.DeserializeObject<ClassName>(result);

this will give you anything you need. 这将为您提供所需的任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM