To_json (rails) similar function for ASP.NET MVC / .NET

In rails, you can do the following to convert an object to Json, but only with a subset of the fields included in the object.

@user.to_json :only => [ :name, :phone ]

      

Although I am currently using the ASP.NET MVC Json () function, it does not allow me to determine which fields I want to include in the transformation. So my question is, is there a function in JSON.NET or otherwise that will accept certain fields before doing the conversion to json.

Edit: Your answer must also cover the array scenario, i.e.

@users.to_json :only => [ :name, :phone ]

      

+2


source to share


3 answers


You can use anonymous types:

public ActionResult SomeActionThatReturnsJson()
{
    var someObjectThatContainsManyProperties = GetObjectFromSomeWhere();
    return Json(new {
        Name = someObjectThatContainsManyProperties.Name,
        Phone = someObjectThatContainsManyProperties.Phone,
    });
}

      

will return {"Name":"John","Phone":"123"}




UPDATE:

The same technique can be used to script an array:

public ActionResult SomeActionThatReturnsJson()
{
    var users = from element in GetObjectsFromSomeWhere()
                select new {
                    Name = element.Name,
                    Phone = element.Phone,
                };
    return Json(users.ToArray());
}

      

+3


source


Here's a way to expand:

    public static string ToJSONArray<T>(this IEnumerable<T> list)
    {
        DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(IEnumerable<T>));
        MemoryStream ms = new MemoryStream();
        s.WriteObject(ms, list);
        return GetEncoder().GetString(ms.ToArray());
    }

    public static IEnumerable<T> FromJSONArray<T>(this string jsonArray)
    {
        if (string.IsNullOrEmpty(jsonArray)) return new List<T>();

        DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(IEnumerable<T>));
        MemoryStream ms = new MemoryStream(GetEncoder().GetBytes(jsonArray));
        var result = (IEnumerable<T>)s.ReadObject(ms);
        if (result == null)
        {
            return new List<T>();
        }
        else
        {
            return result;
        }
    }

      



This is for arrays, but you can easily adapt it.

+1


source


With Json.NET, you can put [JsonIgnore] attributes on properties that you don't want to serialize.

0


source







All Articles