Bil Simser
Bil Simser

Reputation: 1723

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

I have some JSON which is valid but a little quirky looking. 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.

I'm using JSON.NET and C# so please don't provide an answer that requires the JavaScriptSerializer from System.Web.Extensions.dll. Either pure JObject/JToken calls or JConvert.DeserializeObject<> would be okay.

Thanks.

Upvotes: 1

Views: 216

Answers (3)

wollnyst
wollnyst

Reputation: 1931

How about using dynamic deserialization? See Deserialize json object into dynamic object using Json.net

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

Upvotes: 2

user437329
user437329

Reputation:

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);

Upvotes: 2

sadegh saati
sadegh saati

Reputation: 1170

You must define a class like this:

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

and define ClassName2:

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

and finally ClassName3

ClassName3
{
    public string source;
    public string format;
}

supporse you have saved your json data in a string variable like 'result'

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

this will give you anything you need.

Upvotes: 1

Related Questions