Read a value inside a complex JSON in C #

2

Good morning everyone! I am new to C # and am having a hard time getting a value inside a complex Json. Json is this:

 {
  "id": "58e50b82-50b1-4f29-a2e8-a9a544013255",
  "timestamp": "2018-06-20T18:00:12.935Z",
  "lang": "pt-br",
  "result": {
    "source": "agent",
    "resolvedQuery": "me conte uma novidade",
    "action": "",
    "actionIncomplete": false,
    "parameters": {
      "news": "novidade"
    }
}

So far I can only collect the first 3 Json data (id, timestamp and lang) with the following code:

API class:

[HttpPost]
[Route("consumindoApi")]
public HttpResponseMessage DirecionarResposta(Dialogflow dialogflow)
{
  try
  {
      return Request.CreateResponse(HttpStatusCode.OK,  
                    @"ID: " + dialogflow.id + 
                    ". Idioma: " + dialogflow.lang + 
                    ". ID da Sessão: " + dialogflow.sessionId + 
                    ". Horario da mensagem: " + dialogflow.timestamp);
   }
   catch (Exception e)
   {
      return Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
   }
 }

Model class that I use to map Json:

public class Dialogflow
    {
        public string id { get; set; }
        public string timestamp { get; set; }
        public string lang { get; set; }
        public string sessionId { get; set; }
        public string result { get; set; }
    }

I use Newtonsoft to do this manipulation, but since I'm new to the piece, I can not collect the data inside the result and parameters list. How would I do to be able to collect the values of the fields within these two lists?

    
asked by anonymous 25.06.2018 / 14:45

1 answer

3

result is another object, it can not be string . Also, parameters is also an object. The structure would look like this:

public class Parameters
{
    public string news { get; set; }
}

public class Result
{
    public string source { get; set; }
    public string resolvedQuery { get; set; }
    public string action { get; set; }
    public bool actionIncomplete { get; set; }
    public Parameters parameters { get; set; }
}

public class Dialogflow
{
    public string id { get; set; }
    public DateTime timestamp { get; set; }
    public string lang { get; set; }
    public Result result { get; set; }
}

You can also do this without creating the classes, using dynamic , like this:

 dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

See the example: link

More about dynamic : csharp / language-reference / keywords / dynamic

    
25.06.2018 / 14:50