Consume a JSON result (beginner)

Asked

Viewed 57 times

0

Hello, I have a very simple test. A method returns a JSON(), but how I access the values within this return?

In the Test method I would like to use some value of the returned JSON. Could you help? Thank you.

namespace DGBar.Controllers {
  public class TestController : ApiController {
    [HttpGet]
    public IHttpActionResult Index() {
      return Json(new { Nome = "Rafael", Idade = 34 });
    }
    [Route("teste")]
    [HttpGet]
    public IHttpActionResult Teste() {
      var result = Index();
      return Json(JsonConvert.DeserializeObject(result).Nome);
    }
  }
}
  • I don’t think it’s gonna work that way... the method Index() will return an Htttpactionresult and not the object you are trying to deserialize... you would have to make a request in the method Teste() or prepare it to receive Json as parameter/argument.

  • Thank you for the strength. I really needed to make some Sts to succeed. Here’s how I did it.

2 answers

0


I got it, but I couldn’t get it using anonymous class.

Follow the result.

[Route("teste")]
[HttpGet]
public IHttpActionResult Teste() {
  var result = Index();
  var contentResult = ((System.Web.Http.Results.JsonResult<TestController.Content>)result).Content;
  return Json(contentResult.Nome);
}
  • but it still doesn’t make sense... why are you directly accessing an action that returns a json to deseralize and then return another JSON... what you’re trying to do

  • I am just trying to test the result of a method that returns a JSON. In this way I was able to return the JSON to the original object and then I can buy the properties.

-1

In this example below I am deserializing the json in a string

string result = Jsonconvert.Deserializeobject(result);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.