2009-08-06 16 views
5

He escrito un servicio web simple que consigue lista de productos en JSONText que es objeto de cadena de código de servicioASP.NET JSON servicio web Respuesta formato

Web está por debajo

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.Services; 
using System.Web.Script.Services; 
using System.Runtime.Serialization.Json; 
using System.IO; 
using System.Text; 

/// <summary> 
/// Summary description for JsonWebService 
/// </summary> 
[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.Web.Script.Services.ScriptService] 
public class JsonWebService : System.Web.Services.WebService 
{ 

    public JsonWebService() { 

     //Uncomment the following line if using designed components 
     //InitializeComponent(); 
    } 

    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string GetProductsJson(string prefix) 
    { 
     List<Product> products = new List<Product>(); 
     if (prefix.Trim().Equals(string.Empty, StringComparison.OrdinalIgnoreCase)) 
     { 
      products = ProductFacade.GetAllProducts(); 
     } 
     else 
     { 
      products = ProductFacade.GetProducts(prefix); 
     } 
     //yourobject is your actula object (may be collection) you want to serialize to json 
     DataContractJsonSerializer serializer = new DataContractJsonSerializer(products.GetType()); 
     //create a memory stream 
     MemoryStream ms = new MemoryStream(); 
     //serialize the object to memory stream 
     serializer.WriteObject(ms, products); 
     //convert the serizlized object to string 
     string jsonString = Encoding.Default.GetString(ms.ToArray()); 
     //close the memory stream 
     ms.Close(); 
     return jsonString; 
    } 
} 

ahora dame resoponse como abajo:

{"d": "[{\" ProductID \ ": 1, \" ProductName \ ": \" Producto 1 \ "}, {\" ProductID \ ": 2, \" ProductName \ ": \" Producto 2 \ "}, {\" ProductID \ ": 3, \" ProductName \ ": \" Producto 3 \ "}, {\" ProductID \ ": 4, \" ProductName \ ": \ "Producto 4 \"}, {\ "ProductID \": 5, \ "ProductName \": \ "Producto 5 \"}, {\ "ProductID \": 6, \ "ProductName \": \ "Producto 6 \"}, {\ "ProductID \ ": 7, \" ProductName \ ": \" Producto 7 \ "}, {\" ProductID \ ": 8, \" ProductName \ ": \" Producto 8 \ "}, {\" ProductID \ ": 9 , \ "ProductName \": \ "Producto 9 \"}, {\ "ProductID \": 10, \ "ProductName \": \ "Producto 10 \"}] "}

Pero estoy buscando debajo pone

[{"ProductID": 1, "ProductName": "Producto 1"}, {"ProductID": 2, "ProductName": "Producto 2"}, {"ProductID": 3, "ProductName": "Producto 3"}, {"ProductID": 4, "ProductName": "Producto 4"}, {"ProductID": 5, "ProductName": "Producto 5"}, {"ProductID": 6 , "ProductName": "Product 6"}, {"ProductID": 7, "ProductName": "Product 7"}, {"ProductID": 8, "ProductName": "Product 8"}, {"ProductID": 9, "ProductName": "P roducto 9 "}, {" ProductID ": 10," ProductName ":" 10" Producto}]

puede alguien decirme lo que es un problema real

Gracias

Respuesta

7

Primero hubo un cambio con ASP.NET 3.5 por razones de seguridad Microsoft agregó la "d" a la respuesta. Debajo hay un enlace de Dave Ward en Encosia que habla sobre lo que está viendo: A breaking change between versions of ASP.NET AJAX. Él tiene varios puestos que habla de esto que puede ayudarle aún más con JSON procesamiento y ASP.NET

+0

Gracias ewrankin por su amable respuesta pero mi problema es que tengo que ir con el framework asp.net 2.0 así que por favor sugiéranme cómo puedo lograrlo. por favor, si usted tiene alguna otra opción que por favor dígame – Hiscal

+0

Lo siento, supongo que no entiendo su comentario. ¿Quieres ir a ASP.NET 2.0? Debido a que según la respuesta JSON que recibe, está utilizando ASP.NET 3.5 debido a la "d" adicional que se está agregando. ¿O está preguntando cómo trabajar con la "d" en la respuesta que está recibiendo? – ewrankin

+0

He trabajado con tu sugerencia pero aún así me da el mismo resultado con "\" no deseado y no me da salida como {"d": "[{" ProductID ": 1," ProductName ":" Product 1 " }, {"ProductID": 2, "ProductName": "Product 2"}, {"ProductID": 3, "ProductName": "Product 3"}, {"ProductID": 4, "ProductName": "Product 4 "}, {" ProductID ": 5," ProductName ":" Producto 5 "}, {" ProductID ": 6," ProductName ":" Producto 6 "}, {" ProductID ": 7," ProductName ":" Producto 7 "}, {" ProductID ": 8," ProductName ":" Producto 8 "}, {" ProductID ": 9," ProductName ":" Producto 9 "}, {" ProductID ": 10," ProductName ":" Producto 10 "}]"} – Hiscal

0

En realidad, si usted acaba de quitar la

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

del método, y que devuelva el jsonString que Si serializaste usando JavaScriptSerializer obtendrás exactamente el resultado que estabas buscando.

+2

Tengo el mismo problema, pero si elimino este ResponseFormat, la salida se envuelve con una nueva etiqueta:

-1

en servicio web .NET

 [WebMethod] 
     public string Android_DDD(string KullaniciKey, string Durum, string PersonelKey) 
     { 
     return EU.EncodeToBase64("{\"Status\":\"OK\",\"R\":[{\"ImzaTipi\":\"Paraf\", \"Personel\":\"Ali Veli üğişçöıÜĞİŞÇÖI\", \"ImzaDurumTipi\":\"Tamam\", \"TamamTar\":\"1.1.2003 11:21\"},{\"ImzaTipi\":\"İmza\", \"Personel\":\"Ali Ak\", \"ImzaDurumTipi\":\"Tamam\", \"TamamTar\":\"2.2.2003 11:21\"}]}"); 
     } 

static public string EncodeToBase64(string toEncode) 
    { 
     UTF8Encoding encoding = new UTF8Encoding(); 
     byte[] bytes = encoding.GetBytes(toEncode); 
     string returnValue = System.Convert.ToBase64String(bytes); 
     return returnValue; 
    } 

en Android

private static String convertStreamToString(InputStream is) 
    { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try 
     { 
      while ((line = reader.readLine()) != null) 
      { 
       sb.append(line + "\n"); 
      } 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
     finally 
     { 
      try 
      { 
       is.close(); 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 

private void LoadJsonDataFromASPNET() 
    { 
     try 
     {   

      DefaultHttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httpPostRequest = new HttpPost(this.WSURL + "/WS.asmx/Android_DDD"); 

      JSONObject jsonObjSend = new JSONObject(); 
      jsonObjSend.put("KullaniciKey", "value_1"); 
      jsonObjSend.put("Durum", "value_2"); 
      jsonObjSend.put("PersonelKey", "value_3"); 

      StringEntity se = new StringEntity(jsonObjSend.toString()); 
      httpPostRequest.setEntity(se); 
      httpPostRequest.setHeader("Accept", "application/json"); 
      httpPostRequest.setHeader("Content-type", "application/json"); 
      // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression 

      HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); 
      HttpEntity entity = response.getEntity(); 
      if (entity != null) 
      { 
       InputStream instream = entity.getContent(); 
       String resultString = convertStreamToString(instream); 
       instream.close(); 

       resultString = resultString.substring(6, resultString.length()-3); 
       resultString = new String(android.util.Base64.decode(resultString, 0), "UTF-8"); 
       JSONObject object = new JSONObject(resultString); 
       String oDurum = object.getString("Status"); 
       if (oDurum.equals("OK")) 
       { 
        JSONArray jsonArray = new JSONArray(object.getString("R")); 
        if (jsonArray.length() > 0) 
        { 
         for (int i = 0; i < jsonArray.length(); i++) 
         { 
          JSONObject jsonObject = jsonArray.getJSONObject(i); 
          String ImzaTipi = jsonObject.getString("ImzaTipi"); 
          String Personel = jsonObject.getString("Personel"); 
          String ImzaDurumTipi = jsonObject.getString("ImzaDurumTipi"); 
          String TamamTar = jsonObject.getString("TamamTar"); 
          Toast.makeText(getApplicationContext(), "ImzaTipi:" + ImzaTipi + " Personel:" + Personel + " ImzaDurumTipi:" + ImzaDurumTipi + " TamamTar:" + TamamTar, Toast.LENGTH_LONG).show(); 
         } 
        } 
       }    

      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 
+0

Espera, ¿qué ????? – Dementic

+0

cuando json object pasa la aplicación .net a androi (con [ScriptMethod (ResponseFormat = ResponseFormat.Json)]) la respuesta de android tiene

+0

Tu código no es relevante para la pregunta. – Dementic

0

en cuenta que u tiene comillas dobles junto a ur matriz en su response.In esta manera la vuelta de u formato JSON no objeto JSON de ur método web.El formato de Json es una cadena.Por lo tanto, debe utilizar la función json.parse() para analizar la cadena json al objeto json.Si no desea utilizar la función de análisis sintáctico, debe eliminar la serialización en su método web.Así obtienes un objeto json.

+0

no tienes que agregar el método de respuesta en tu método web. Si envías tus parámetros en formato json como este" { 'prefix': 'asd'} ",. net devolverá la respuesta en jsonobject. De lo contrario, si envía sus datos en un objeto codificado en forma o json como este {'prefix': 'asd'} sin comillas dobles. Los datos vendrán envuelto en xml. Así que tienes que usar el formato de respuesta en este momento – Onr

Cuestiones relacionadas