-1

I am calling the CodeCollaborator API using Json.Net from a C# program.

I am receiving the following JSON in an HttpResponse from the API.

[{"result":{"loginTicket":"c9c6793926517db05bde47d3dd50026e"}}]

How can I parse it to create the LoginTicketResponse object mentioned below?

public class LoginTicketResponse
{
    public string loginTicket { get; set; }
}

I tried the following code but no luck.

JArray a = JArray.Parse(result);
foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {                        
        dynamic stuff = JsonConvert.DeserializeObject(p.ToString());
    }
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Ram
  • 11,404
  • 15
  • 62
  • 93

2 Answers2

1

You are not far off. In your inner loop change this line:

dynamic stuff = JsonConvert.DeserializeObject(p.ToString());

to this:

LoginTicketResponse stuff = p.Value.ToObject<LoginTicketResponse>();

Or if you know that there will only be one item in the response, you can simplify the whole thing to this:

JArray a = JArray.Parse(result);
LoginTicketResponse stuff = a[0]["result"].ToObject<LoginTicketResponse>();
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
-1

You might benefit much from JSON.NET it's a NuGet package which is easy to install. With that package you can easily write:

JsonConvert.DeserializeObject<LoginTicketResponse>(jsonString);
Xander
  • 1
  • OP is already using Json.Net; it says so in the question. Also, the line of code you wrote will not correctly parse the JSON given in the question, as the `LoginTicketResponse` is inside an object which is inside an array. – Brian Rogers Oct 09 '15 at 14:36