首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >与[DataMember(Name=“JsonResult”)]等效的测试

与[DataMember(Name=“JsonResult”)]等效的测试
EN

Stack Overflow用户
提问于 2010-11-25 01:22:28
回答 2查看 2K关注 0票数 4

我有一个方法可以做到这一点:

代码语言:javascript
复制
public JsonResult Layar(string countryCode, string timestamp, string userId, 
                        string developerId, string layarName, double radius, 
                        double lat, double lon, double accuracy)
{
    LayarModel model = new LayarModel(lat, lon, radius);

    return Json(model, JsonRequestBehavior.AllowGet);
}

它返回这个对象:

代码语言:javascript
复制
public class LayarModel
{        
    private List<HotSpot> _hotSpots = new List<HotSpot>();
    public List<HotSpot> HotSpots { get { return _hotSpots; } set { _hotSpots = value; } }    
    public string Name { get; set; }    
    public int ErrorCode { get; set; }
    public string ErrorString { get; set; }
}

我希望JSON是

代码语言:javascript
复制
{"hotspots": [{
    "distance": 100, 
    "attribution": "The Location of the Layar Office", 
    "title": "The Layar Office",  
    "lon": 4884339, 
    "imageURL": http:\/\/custom.layar.nl\/layarimage.jpeg,
    "line4": "1019DW Amsterdam",
    "line3": "distance:%distance%",
    "line2": "Rietlandpark 301",
    "actions": [],
    "lat": 52374544,
    "type": 0,
    "id": "test_1"}], 
 "layer": "snowy4",
 "errorString": "ok", 
 "morePages": false,
 "errorCode": 0,
 "nextPageKey": null
} 

返回的类中的所有内容都是大写的(用hotspots代替HotSpots)。

我试过DataContract和DataMembers(Name=“测试”),但不起作用。有什么建议吗?

EN

回答 2

Stack Overflow用户

发布于 2010-12-01 23:55:16

JsonResult()在内部使用JavaScriptSerializer进行序列化,并且它似乎不支持使用属性定义序列化的属性名称。

DataContractJsonSerializer支持这一点,因此这可能是一条可行的道路。

一些可能有用的链接:

:更改字段名: JavaScriptSerializer

票数 1
EN

Stack Overflow用户

发布于 2013-04-13 01:45:04

我也推荐安装json.NET,但剩下的要容易得多。下面是我在当前应用程序中使用的一个扩展方法,以提供更好的重用,您可以随意调整它以满足您的需求,但它应该可以立即完成您需要的功能。

代码语言:javascript
复制
public class JsonNetResult : ActionResult
{
    public Encoding ContentEncoding { get; set; }
    public string ContentType { get; set; }
    public object Data { get; set; }

    public JsonSerializerSettings SerializerSettings { get; set; }
    public Formatting Formatting { get; set; }

    public JsonNetResult()
    {
        SerializerSettings = new JsonSerializerSettings
            {
                //http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
                #if DEBUG
                Formatting = Formatting.Indented, //Makes the outputted Json easier reading by a human, only needed in debug
                #endif
                ContractResolver = new CamelCasePropertyNamesContractResolver() //Makes the default for properties outputted by Json to use camelCaps
            };
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        HttpResponseBase response = context.HttpContext.Response;

        response.ContentType = !string.IsNullOrEmpty(ContentType)
                                    ? ContentType
                                    : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        if (Data != null)
        {
            JsonTextWriter writer = new JsonTextWriter(response.Output) {Formatting = Formatting};

            JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
            serializer.Serialize(writer, Data);

            writer.Flush();
        }
    }
}

public static class JsonNetExtenionMethods
{
    public static ActionResult JsonNet(this Controller controller, object data)
    {
        return new JsonNetResult() {Data = data};
    }

    public static ActionResult JsonNet(this Controller controller, object data, string contentType)
    {
        return new JsonNetResult() { Data = data, ContentType = contentType };
    }

    public static ActionResult JsonNet(this Controller controller, object data, Formatting formatting)
    {
        return new JsonNetResult() {Data = data, Formatting = formatting};
    }
}

这里有一个使用它的例子。

代码语言:javascript
复制
public JsonNetResult Layar(string countryCode, string timestamp, string userId, 
                        string developerId, string layarName, double radius, 
                        double lat, double lon, double accuracy)
{
    LayarModel model = new LayarModel(lat, lon, radius);

    return this.JsonNet(model);
}

JsonSerializerSettings上的ContractResolver设置为使用new CamelCasePropertyNamesContractResolver()时,需要特别注意的是解决问题的部分

这样您就再也不必设置自定义命名了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4269615

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档