0

I am using ASP.net Core web api (c#) here

I have a JSON string as:

{
   "userId":321,   
   "account":"new  
   "fname":"Adam",
   "lname":"Silver" 
   "features":[
      {
         "available":true,
         "status":open,
         "admin":false        
      }
   ]
}

I want to test this data in my angular code so wanted to hardcode this into my API; then I want my API to return this back. What I am finding it hard is how to return this. Shall I return this as a string or need to parse it?

I have this method in my API:

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

Do I need to represent this into string or parse it someway?

9
  • Why are you finding it hard what's the issue here that you are facing not clear from the question Commented Jun 6, 2019 at 13:10
  • There's no such thing as "a JSON". JSON is a text format for sending data across the wire. You either have an object, or you have a string. If you have an object, use return Json(obj). If you have a string, set the content type header to "application/json". Commented Jun 6, 2019 at 13:11
  • Sorry I am using asp.net core web api and then using angular as the front end for consuming this. Like the above default api is returning value1 and value2. I wanted to know how can I format my above json to return in the same manner. Commented Jun 6, 2019 at 13:16
  • 1
    Create a class structure that represents the JSON structure you want to return. Then create an instance of that class, and return it from your action method. Change the return type of your method to match what you're returning. Commented Jun 6, 2019 at 13:19
  • Mason is right. Forget about creating the JSON directly within Web API. Create an object with the correct structure, and return it. Web API will serialise it to JSON automatically for you. Commented Jun 6, 2019 at 13:20

3 Answers 3

1

Your JSON is invalid. We need to correct it. JSONLint can be helpful for that. I took your JSON and corrected the syntax errors until I got this:

{
   "userId": 321,   
   "account": "new",
   "fname": "Adam",
   "lname": "Silver",
   "features":[
      {
         "available": true,
         "status": "open",
         "admin": false        
      }
   ]
}

Then I need to generate a C# class structure to represent this JSON. I could manually create it, but the excellent json2csharp.com can generate it for me quickly. I fed this JSON into and received the following classes back:

public class Feature
{
    public bool available { get; set; }
    public string status { get; set; }
    public bool admin { get; set; }
}

public class RootObject
{
    public int userId { get; set; }
    public string account { get; set; }
    public string fname { get; set; }
    public string lname { get; set; }
    public List<Feature> features { get; set; }
}

I put these class definitions into my application. Then I need to modify my action method to create an instance of this RootObject class (you should change the name to actually match what it's intended for).

[HttpGet]        
public ActionResult<RootObject> Get()
{
    // Create an instance of our RootObject and set the properties
    var myRootObject = new RootObject();
    myRootObject.userId = 321;
    myRootObject.account = "new";
    myRootObject.fname = "Adam";
    myRootObject.lname = "Silver";
    myRootObject.features = new List<Feature>();

    // Create an instance of a feature and set its properties
    var feature = new Feature();
    feature.available = true;
    feature.status = "open";
    feature.admin = false;

    // Add the new feature to the features collection of our RootObject    
    myRootObject.features.Add(feature);

    // Return the instance of our RootObject
    // The framework will handle serializing it to JSON for us
    return myRootObject;
}

Note that I changed the signature of your method. I made it no longer accept an IEnumerable because it wasn't clear why you had that. And I changed it to return an ActionResult after checking Microsoft's documentation.

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

Comments

1

Hi Please find correct JSON format for above one:

{
    "userId": 321,
    "account": "new",
    "fname": "Adam",
    "lname": "Silver",
    "features": [{
        "available": true,
        "status": "open",
        "admin": false
    }]
}

you can use below class in your web API to pass respective data

public class Feature
{
    public bool available { get; set; }
    public string status { get; set; }
    public bool admin { get; set; }
}

public class RootObject
{
    public int userId { get; set; }
    public string account { get; set; }
    public string fname { get; set; }
    public string lname { get; set; }
    public List<Feature> features { get; set; }
}

then at the end, while returning data, convert the respective class object into JSON by serializing that into JSON format.

Hope it will fulfill your requirement.

12 Comments

How will it return in serilaize/return in the format of my json
@karen You would create an instance of the RootObject, then return that instance from your action method. The framework handles serialization for you.
and where shall I assign the values to this.
You shouldn't assume when assisting someone that they have access to your custom source code. Also, it makes no sense to have void as the return type from your action method. And there would be no reason to generate a WebRequest.....
@karen, you need to create an instance of public List<Feature> features { get; set; } as well.
|
-1

Putting the comments into an answer: If you are using ActionResult, I'll assume you are using asp.net mvc. What you want is JsonResult.

    [HttpGet]
    public JsonResult Get()
    {
        return new JsonResult
        {
            Data = new
            {
                userId = 321,
                account = new
                {
                    fname = "Adam",
                    lname = "Silver",
                    features = new object[]{
                    new
                {
                    available = true,
                    status = "open",
                    admin = false
                }
                }
                }
            },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }

2 Comments

No, turns out it's ASP.NET Core Web API, which does have an ActionResult
I specifically held off on answering until I was sure what framework was being used. If a question isn't clear, then wait until it's clear before attempting an answer. If you have enough reputation to comment, then you can work with the asker to obtain any clarifications needed.

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.