mach
mach

Reputation: 111

Deserialize json containing csv file as response

I get the following response

{
    "url": "https://XXX/plugins/servlet/export/exportAttachment?fileName=Cycle-SPRINT+19.csv"
}

I am using this class

public class csvBody
{
    public string url { get; set; }    
}

and the following code

WebResponse response = (HttpWebResponse) request.GetResponse();
Stream newStream = response.GetResponseStream();
StreamReader sr = new StreamReader(newStream);
String resJson = sr.ReadToEnd();

var dict = JsonConvert.DeserializeObject<Dictionary<string, csvBody>>(resJson);

But getting the following error

Newtonsoft.Json.JsonSerializationException: 'Error converting value "https://xxx/plugins/servlet/export/exportAttachment?fileName=Cycle-SPRINT+19.csv" to type 'ReadCSV.csvBody'. Path 'url', line 1, position 101.'

Please let me know the correct way to deserialize this json response.

Upvotes: 3

Views: 373

Answers (1)

Gaurang Dave
Gaurang Dave

Reputation: 4046

There is no need of creating Dictionary<string, csvBody>. I tested with same json string and following solution will work for you.

You can access url using dict.url.

Important thing is that API is only returning path of CSV file not content.

static void Main(string[] args)
{
    string json = "{ \"url\": \"https://XXX/plugins/servlet/export/exportAttachment?fileName=Cycle-SPRINT+19.csv\" }";

     var dict = JsonConvert.DeserializeObject<csvBody>(json);

     Console.ReadLine();
}

Upvotes: 3

Related Questions