Lord Relix
Lord Relix

Reputation: 942

Deserializing JSON Data with JSON.NET

I am having trouble working with an API, first time I've worked with one. I've managed to use GET to read the data I need and that part is working perfectly, now I need to deserialize the JSON data I am getting back, and I am using Newtonsoft's JSON .NET library. The problem seems to come when I deserialize the data as its exploding and the debugger isn't being helpful. I tried a few suggestions online but no go, so if someone can enlighten me it'd be appreciated. This is the code:

 string url = "";
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 Stream receiveStream = response.GetResponseStream();
 StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

 string responseData = readStream.ReadToEnd();

 var results = JsonConvert.DeserializeObject<dynamic>(responseData);
 var id = results["id"].Value;
 // var name = results.Name;

When I run it the debugger throws the following exception at the last line of code:

{"Accessed JArray values with invalid key value: \"id\". Array position index expected."}

I am fairly sure that ID exists in the data I am getting back.

Json data I am getting back from Smarty Streets:

 [
{
    "id": 0,
    "candidate_index": 0,
    "delivery_line_1": "1600 Amphitheatre Pkwy",
    "last_line": "Mountain View CA 94043-1351",
    "delivery_point_barcode": "940431351000",
    "components": {
        "primary_number": "1600",
        "street_name": "Amphitheatre",
        "street_suffix": "Pkwy",
        "city_name": "Mountain View",
        "state_abbreviation": "CA",
        "zipcode": "94043",
        "plus4_code": "1351",
        "delivery_point": "00",
        "delivery_point_check_digit": "0"
    },
   ]

Upvotes: 1

Views: 3952

Answers (3)

nitsram
nitsram

Reputation: 716

Another option is to "Paste JSON as classes" so it can be deserialised quick and easy.

  1. Simply copy your entire JSON
  2. In VS: Click Edit > Paste Special > Paste JSON as classes

Here is a better explanation n piccas... https://blogs.msdn.microsoft.com/webdev/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc/

Upvotes: 1

L.B
L.B

Reputation: 116178

Your response is an array not a single object. So You should use

JArray results = JArray.Parse(responseData)

to parse the result (like results[0]["id"]). If you go the dynamic way then

dynamic results = JArray.Parse(responseData)

Now, you can use it like results[0].id

Upvotes: 2

Jason
Jason

Reputation: 3040

Your result appears to be an array of objects, not an array itself. Try setting id to results["id"][0].Value and see if you get something.

See this: Accessed JArray values with invalid key value: "fields". Array position index expected

Upvotes: 0

Related Questions