MVC C#以Json正确的方式来格式化字符串数组中的url?

时间:2012-03-05 18:08:17

标签: json c#-4.0

我正在尝试理解正确的方法来处理通过Json返回的字符串数组中的url中的反斜杠...我已经评论了下面的目标

   public JsonResult PhotosByListingId(int id)
    {
       var pics =  _listingRepository.GetById(id).ListingPhoto.ToList();
       List<string> l = new List<string>();

        foreach(var p in pics)
        {
            //l.Add("albums\\/album1\\/" + p.PhotoName);   //nope
            //l.Add(@"albums\/album1\/" + p.PhotoName);  //nope
            l.Add("albums/album1/" + p.PhotoName); //????? nope
        }

        string[] s = l.ToArray();

        return Json(s, JsonRequestBehavior.AllowGet);

        //needs to be this..THE GOAL
        //  ["albums\/album1\/10k.jpg","albums\/album1\/10l.jpg","albums\/album1\/10y.jpg"]


        //but is returning this?
        // ["albums/album1/10k.jpg","albums/album1/10l.jpg","albums/album1/10y.jpg"]

}

1 个答案:

答案 0 :(得分:0)

您可以尝试string.Replace:

   public JsonResult PhotosByListingId(int id)
{
   var pics =  _listingRepository.GetById(id).ListingPhoto.ToList();
   List<string> l = new List<string>();

    foreach(var p in pics)
    {
        l.Add("albums/album1/".Replace("/", "\\/") + p.PhotoName);
    }

    string[] s = l.ToArray();

    return Json(s, JsonRequestBehavior.AllowGet);
}

因为javascript序列化器正在转换斜杠,所以您可以自己实现序列化并修改生成的JSON:

        public string CustomSerialised()
    {
        string test = "/This/That/The other/";
        List<string> arr = new List<string>();
        arr.Add(test);
        arr.Add(test);
        arr.Add(test);

        System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();

        return s.Serialize(arr).Replace("/","\\/");
    }

在控制器中使用时,可以导航到使用标准路由模式。