user1615362
user1615362

Reputation: 3807

Return object as json

I have this class.

public class SDS
{
    public Guid A { get; set; }

    public Guid B { get; set; }

    public String C { get; set; }
}

I return the json like this

public HttpResponseMessage Val()
        {

                SDS svr = new SDS();
                svr.A = ...
                svr.B = ...
                svr.C = ...

    return Request.CreateResponse(HttpStatusCode.OK, json_serializer.Serialize(svr), "application/json");
}

In the client side I use jquery like this

var obj = jQuery.parseJSON(jqXHR.responseText);

The problem is that the json that gets returned is like this and I am unable to iterate ofer the values or access the elements via index:

{"A":"3a9779fe-9c92-4208-b34d-5113e0548d50","B":"206575a5-8a90-4a13-89ec-910e5a9a35a1","C":"Meta"}

To solve this issue I had to do this and this works:

obj = jQuery.parseJSON('{"List":[' + obj + ']}');

My question is is there any way to use an attribute on the class so that it returns a json that I can use?

[SomeAttribute name="List"]
public class SDS
{
    public Guid A { get; set; }

    public Guid B { get; set; }

    public String C { get; set; }
}

... ... ...

Update2:

This question is still open as none of the provided answers were able to produce a fix.

Upvotes: 0

Views: 1695

Answers (5)

muqi
muqi

Reputation: 1

add ApiController and using System.Web.Http;

Upvotes: 0

D Stanley
D Stanley

Reputation: 152556

Well, you're returning a single object, not a list, but you could do:

public HttpResponseMessage Val()
{

    SDS svr = new SDS();
    svr.A = ...
    svr.B = ...
    svr.C = ...

    var list = new {List = new [] {svr}};

    return Request.CreateResponse(HttpStatusCode.OK, json_serializer.Serialize(svr), "application/json");
}

Upvotes: 0

Anthony Johnston
Anthony Johnston

Reputation: 9584

The JSON returned is correct, don't change anything in your controller

..but in your JS loop the object with a for in loop

for(var propertyName in obj){
     ...
}

propertyName gives you A, B and C and...

var value = obj[propertyName]

gives you the value

Upvotes: 0

felipekm
felipekm

Reputation: 2910

Did you try to use the JsonResult from System.Web.Mvc.JsonResult ?

public JsonResult Val()  {}

Hope this Helps.

Upvotes: 0

jrummell
jrummell

Reputation: 43077

You can return a JsonResult by calling Json() in your action method.

public ActionResult Get(int id)
{
    var item = ...
    return Json(item);
}

Upvotes: 2

Related Questions