[c#] Parsing Json rest api response in C#

I am trying to pull a value from a rest api json response using C#.

I have the following code:

client.BaseUrl = "https://api.cloud.appcelerator.com";
request.Resource = "/v1/chats/create.json?key=" + cac.AppCode.ToString();
request.Method = Method.POST;
request.AddUrlSegment("appkey", "key");
var response = client.Execute(request);

In the "response" message I got a json content as follows:

{
  "meta": {
    "code": 200,
    "status": "ok",
    "method_name": "createChatMessage"
  },
  "response": {
    "chats": [
      {
        "id": "521cfcd840926a0b3500449e",
        "created_at": "2013-08-27T19:24:08+0000",
        "updated_at": "2013-08-27T19:24:08+0000",
        "message": " join to the chat group, welcome …",
        "from": {
          "id": "520f41e125e74b0b2400130a",
          "first_name": "Administrator",
          "created_at": "2013-08-17T09:26:57+0000",
          "updated_at": "2013-08-27T19:23:10+0000",
          "external_accounts": [

          ],
          "email": "[email protected]",
          "confirmed_at": "2013-08-17T09:26:57+0000",
          "username": "admin",
          "admin": "true",
          "stats": {
            "photos": {
              "total_count": 0
            },
            "storage": {
              "used": 0
            }
          }
        },
        "chat_group": {
          "id": "521cfcd840926a0b3500449d",
          "created_at": "2013-08-27T19:24:08+0000",
          "updated_at": "2013-08-27T19:24:08+0000",
          "message": " join to the chat group, welcome …",
          "participate_users": [
            {
              "id": "520f41e125e74b0b2400130a",
              "first_name": "Administrator",
              "created_at": "2013-08-17T09:26:57+0000",
              "updated_at": "2013-08-27T19:23:10+0000",
              "external_accounts": [

              ],
              "email": "[email protected]",
              "confirmed_at": "2013-08-17T09:26:57+0000",
              "username": "admin",
              "admin": "true",
              "stats": {
                "photos": {
                  "total_count": 0
                },
                "storage": {
                  "used": 0
                }
              }
            }
          ]
        }
      }
    ]
  }
}

How do I pull the following nested value of "id": "521cfcd840926a0b3500449e" from the returned json response result message?

I am using C#.

This question is related to c# json rest api parsing

The answer is


Create a C# class that maps to your Json and use Newsoft JsonConvert to Deserialise it.

For example:

public Class MyResponse
{
    public Meta Meta { get; set; }
    public Response Response { get; set; }
}

  1. Create classes that match your data,
  2. then use JSON.NET to convert the JSON data to regular C# objects.

Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below

Step 2: JToken.Parse(...).ToObject<RootObject>().

public class Meta
{
    public int code { get; set; }
    public string status { get; set; }
    public string method_name { get; set; }
}

public class Photos
{
    public int total_count { get; set; }
}

public class Storage
{
    public int used { get; set; }
}

public class Stats
{
    public Photos photos { get; set; }
    public Storage storage { get; set; }
}

public class From
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ParticipateUser
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ChatGroup
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public List<ParticipateUser> participate_users { get; set; }
}

public class Chat
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public From from { get; set; }
    public ChatGroup chat_group { get; set; }
}

public class Response
{
    public List<Chat> chats { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public Response response { get; set; }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to api

I am receiving warning in Facebook Application using PHP SDK Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Failed to load resource: the server responded with a status of 404 (Not Found) css Call another rest api from my server in Spring-Boot How to send custom headers with requests in Swagger UI? This page didn't load Google Maps correctly. See the JavaScript console for technical details How can I send a Firebase Cloud Messaging notification without use the Firebase Console? Allow Access-Control-Allow-Origin header using HTML5 fetch API How to send an HTTP request with a header parameter? Laravel 5.1 API Enable Cors

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?