【问题标题】:JsonResult equivalent to [DataMember(Name="Test")]JsonResult 相当于 [DataMember(Name="Test")]
【发布时间】:2010-11-24 17:22:27
【问题描述】:

我有这样的方法:

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") 但这不起作用。有什么建议吗?

【问题讨论】:

    标签: asp.net json asp.net-mvc-2 jsonresult


    【解决方案1】:

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

    DataContractJsonSerializer 支持这一点,所以这可能是一种方法。

    一些可能有用的链接:

    【讨论】:

      【解决方案2】:

      我还建议安装 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);
      }
      

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-30
        相关资源
        最近更新 更多