4

私はこれを行う方法があります:

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")を試しましたが、機能しません。助言がありますか?

4

2 に答える 2

1

JsonResult() はシリアル化のために内部で JavaScriptSerializer を使用しており、属性を使用したシリアル化されたプロパティ名の定義をサポートしていないようです。

DataContractJsonSerializer はこれをサポートしているので、それが良い方法かもしれません。

役に立つかもしれないいくつかのリンク:

于 2010-12-01T15:55:15.800 に答える
0

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

問題を具体的に解決することに注意する必要があるのはContractResolverJsonSerializerSettingsが使用するように設定されている場合です。new CamelCasePropertyNamesContractResolver()

このようにして、カスタムの命名を再度設定する必要はありません。

于 2013-04-12T17:45:03.537 に答える