开发者

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

开发者 https://www.devze.com 2022-12-08 16:48 出处:网络
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.

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 开发者_Go百科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 ]


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号