views:

171

answers:

3

Hi,

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 using currently the ASP.NET MVC Json() function it doesn't let me define which fields i want to include in the conversion. So my question is whether or not there is a function in JSON.NET or otherwise that will accept specific fields before doing the conversion to json.

Edit: Your answer should also cover the array scenario ie.

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

Here is a extension method:

    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;
        }
    }

It's for Arrays, but you can easily adapt it.

Arthur
+3  A: 

You could 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 for the array scenario:

public ActionResult SomeActionThatReturnsJson()
{
    var users = from element in GetObjectsFromSomeWhere()
                select new {
                    Name = element.Name,
                    Phone = element.Phone,
                };
    return Json(users.ToArray());
}
Darin Dimitrov
check my edit /15chars
Konstantinos
Anonymous types can also be applied to arrays.
Darin Dimitrov
hmm not bad :) /c
Konstantinos
A: 

With Json.NET you can place [JsonIgnore] attributes on properties you don't want serialized.

James Newton-King