JsonResult эквивалентен [DataMember (Name = Test)]

У меня есть способ сделать это:

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

Он возвращает этот объект:

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 был

{"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 = "Test"), но это не сработало. Какие-либо предложения?


person Andy    schedule 24.11.2010    source источник


Ответы (2)


JsonResult () внутренне использует JavaScriptSerializer для сериализации и, похоже, не поддерживает определение сериализованных имен свойств с помощью атрибутов.

DataContractJsonSerializer поддерживает это, так что это может быть подходящим вариантом.

Некоторые ссылки, которые могут быть полезны:

person CGK    schedule 01.12.2010

Я бы также порекомендовал установить json.NET, но остальное намного проще. Ниже приведен метод расширения, который я использую в своем текущем приложении, чтобы обеспечить более удобное повторное использование, не стесняйтесь адаптировать его к своим потребностям, но он должен делать то, что вам нужно, прямо из коробки.

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

Вот пример его использования.

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

Следует отметить, что конкретно решает вашу проблему, когда ContractResolver на JsonSerializerSettings настроен на использование new CamelCasePropertyNamesContractResolver()

Таким образом, вам больше не придется настраивать индивидуальное именование.

person Nick Albrecht    schedule 12.04.2013