简体   繁体   中英

How to parse a JSON array containing a single item nested in another object

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());
    }
}

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>();

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM