Gopal Biswas Gopal Biswas - 6 months ago 16
JSON Question

How to retrieve value from Json string in C#

I'm getting a response like

{ "expires": "Sat, 19 May 2046 04:10:58 +0000", "copy_ref": "SMJNA2wxbGZbnmbnm", "Result": null, "error": null }
base: { "expires": "Sat, 19 May 2046 04:10:58 +0000", "copy_ref": "SMJNA2wxbGZ0aWRibWw2aA", "Result": null, "error": null }
ContentDisposition: null
ContentType: "application/json"
HttpHeaders: {Connection: keep-alive
expires=Tue, 25 May 2021 04:10:58 GMT;
}
IsArray: true
IsSuccessfully: true
IsXml: true
Result: { "expires": "Sat, 19 May 2046 04:10:58 +0000", "copy_ref": "SMJNA2wxbGZbnmbnm", "Result": null, "error": null }
StatusCode: 200


I need the value of "copy_ref" from this response string in C#.

Answer

Here's a small console application showing how you'd retrieve it using Json.NET. In your case the string, "json" would be retrieved from the response.

static void Main()
{
    string json = @"
        { 'expires': 'Sat, 19 May 2046 04:10:58 + 0000', 'copy_ref': 'SMJNA2wxbGZbnmbnm', 'Result': null, 'error': null }";

    JObject jObj = JObject.Parse(json);                 // Parse the object graph
    string copyRef = jObj["copy_ref"].ToString();       // Retrive value by key

    Console.WriteLine(copyRef);
}