10

This is a basic question. I am new to ASP.Net Core so I created a .Net Core Web API project using the template in Visual Studio 2017 and I would like to know how to return a Json string from the Get() function.

The Get() function provided.

    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

I would like to know how to change so it returns a Json string of int variable like the following.

    // GET: api/MOER
    [HttpGet]
    public <<some return type>> Get()
    {
        _MOER = 32;

        return <<return a Json result/string of _MOER>>;
    }

I am have seen the Nuget package Newtonsoft.Json where you serialize/deserialize but I am not sure if its applicable any more with .Net Core.

I have also seen examples where they use JsonResult but when I try to use this approach, the compiler doesn't know what Json() is.

    [HttpGet]
    public JsonResult Get()
    {
        _MOER = 32;

        return Json(_MOER);
    }

Thank you for your help!

1
  • It seems that you're using the [ApiController], why not simply return an IActionResult type? Commented Nov 20, 2018 at 1:40

1 Answer 1

17

Add this attribute to your controller class:

[Produces("application/json")]

So it becomes:

[Produces("application/json")]
public class YourController: Controller {

   [HttpGet]
   public IEnumerable<string> Get()
   {
       return new string[] { "value1", "value2" };
   }
}

That should be enough, otherwise I believe the default is XML (unless the client explicitly asks for JSON using the Accept HTTP header).

Sign up to request clarification or add additional context in comments.

5 Comments

Ok but I would like to know how to return a Json string so it returns something like { "key":"value"}
Then you need to change your method so it returns a key/value type, like a Dictionary<string, string>. A list of strings will just be serialized to a plain string array.
Can't I just use the Newtonsof.Json's Serialize/Deserialize for returning a class? (So you know, I'm not interested returning "value1", "value2")
oh, so you are saying if I return a Dictionary, then it will return as a json string. So does that mean everything returned by a Get are always in json string?
Yes, it will always return whatever the return type is, serialized to JSON. If you have a class called Foo with two string properties, Bar and Baz, the result will be: { "Bar":"value of bar", "Baz":"value of baz" } Just try it out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.