Felipe Oliveira Felipe Oliveira - 1 month ago 6
JSON Question

Deserialize JSON in C# to array

I'm having trouble doing deserialize a certain json I am collecting a website.

{
"query": {
"search": [
{
"ns": 0,
"title": "test",
"snippet": "test"
},
{
"ns": 0,
"title": "test2",
"snippet": "test2"
},
{
"ns": 0,
"title": "test3",
"snippet": "test3"
},
{
"ns": 0,
"title": "test4",
"snippet": "test4"
}
]
}
}


This is the class that I'm trying to deserialize into:

private void DesURL_Click(object sender, RoutedEventArgs e)
{
string url = @"https://pt.wikipedia.org/w/api.php.....";

var json = new WebClient().DownloadString(url);

var listaURL = JsonConvert.DeserializeObject<List<Query>>(json);

}


when trying to run the code of an error that this json should be deserialized into an array. Ai trying utiilizar JArray the method I need to do the deserialize before you can turn into array.

The goal is to convert the title and snippet to string in order to extract information from it.

Answer

Pro tip for you: Select your JSON and copy it to the clipboard. Now go to Visual Studio and on the Edit menu, Paste Special and then Paste JSON as Classes. that will give you this:

public class Rootobject
{
    public Query query { get; set; }
}

public class Query
{
    public Search[] search { get; set; }
}

public class Search
{
    public int ns { get; set; }
    public string title { get; set; }
    public string snippet { get; set; }
}

And now you can deserialise like this:

var listaURL = JsonConvert.DeserializeObject<Rootobject>(json);