2012-07-02 13 views
5

tengo una API web C#, dentro de ella tengo datos que es un enlace, por ejemplo: images/Chinese/AbaloneEggCustard.jpgExtracción barra de Web API JSON C#

pero en JSON, que aparecen así:

[{"BackgroundImage":"images\/Chinese\/AbaloneEggCustard.jpg", ......}] 

¿Puedo saber cómo puedo eliminar la barra oblicua? Lo necesito eliminar así que con suerte puedo acceder a las imágenes cuando me conecto con azul.


Aquí está mi controlador códigos:

public IEnumerable<Food> Get() 
    { 
     List<Food> Cases = new List<Food>(); 
     try 
     { 
      string connectionString = ConfigurationManager.ConnectionStrings["HealthyFoodDBConnectionString"].ConnectionString; 
      myConnection = new SqlConnection(connectionString); 
      myConnection.Open(); 

      string sql = "SELECT * from [Recipe] "; 

      myCommand = new SqlCommand(sql, myConnection); 
      myDataReader = myCommand.ExecuteReader(); 

      while (myDataReader.Read()) 
      { 
       Cases.Add(new Food() 
       { 
        RecipeID = (int)myDataReader["RecipeID"], 
        RecipeTitle = (string)myDataReader["RecipeTitle"], 
        FoodCategoryID = Convert.ToInt32(myDataReader["FoodCategoryId"]), 
        Serves = (string)myDataReader["Serves"], 
        PerServing = (string)myDataReader["PerServing"], 
        Favourite = ((Convert.ToInt32(myDataReader["Favourite"]) == 1) ? true : false), 
        Directions = (string)myDataReader["Directions"], 
        BackgroundImage = (string)myDataReader["BackgroundImage"], 
        HealthyTips = (string)myDataReader["HealthyTips"], 
        Nutritions = (string)myDataReader["Nutritions"], 
        Ingredients = (string)myDataReader["Ingredients"] 
       }); 
      } 
     } 
     finally 
     { 
      if (myConnection != null) 
       myConnection.Close(); 
     } 
     return Cases; 
    } 

aquí está mi código Index.cshtml:

<script language="javascript" type="text/javascript"> 
    $(document).ready(function() { 
     // Send an AJAX request 
     $.getJSON("api/food/", 
     function (data) { 
      // on success, 'data' contains a list of products 
      $.each(data, function (key, val){ 

       //format the text to display 
       var str = val.RecipeTitle + ' | ' + val.FoodCategoryID + ' | ' + val.Serves + ' | ' + val.PerServing + ' | ' + val.Favourites + ' | ' + val.Directions + ' | ' + val.BackgroundImage + ' | ' + val.HealthyTips + ' | ' + val.Nutritions + ' | ' + val.Ingredients; 

       // add a list item for the product 
       $('<li/>', { html: str }).appendTo($('#cases')); 

      }); 
     }); 
    }); 
+1

cuales barra invertida se refería a su? –

+0

barra diagonal = barra diagonal? –

+0

barra diagonal = \ barra inclinada =/ – forsakenedsj

Respuesta

1

Suponiendo que está llamando a la API, y volver el objeto JSON normalmente escapado:

var myObject = Foo.API.Call(); //returns object with BackgroundImage property. 

If y sted guardar el resultado en un archivo de texto, puede utilizar JavaScriptSerializer:

var bg = new JavaScriptSerializer().Deserialize(myObject); 
using (var writer = new StreamWriter(@"C:\foo.txt")) 
{ 
    writer.Write(bg.BackgroundImage); 
} 

El archivo de texto guardado debería ser la cadena sin escapar.

+0

pero si quiero mostrar en JSON sin barra invertida que es esta \, ¿cómo se supone que debo hacer? ¿Tiene que ver con getjson? – forsakenedsj

+0

Disculpa, no entendiste tu pregunta, no vi ninguna barra invertida en la publicación original. '/' necesita ser escapado en JavaScript y JSON, por lo que se requiere '' \ '', pero desaparecerá cuando se vuelva a deserializar en un objeto CLR o se interpretará correctamente como un objeto JSON. – lukiffer

+0

Entonces, ¿cómo voy a tratar con \ porque si guardo como un archivo de texto todavía tengo \. O no hay forma? – forsakenedsj

0

Puede utilizar esta:

string deserializedString = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(serializedString); 
Cuestiones relacionadas