2009-08-06 18 views
5

ho scritto un servizio web semplice, che ottiene l'elenco dei prodotti in JSONText che è oggetto stringa di codice ServizioASP.NET JSON Web Service Response formato

Web è al di sotto

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

ora dammi resoponse come sotto:

{"d": "[{\" ProductID \ ": 1, \" ProductName \ ": \" Prodotto 1 \ "}, {\" IDProdotto ": 2, \" NomeProdotto \ ": \" Prodotto 2 \ "}, {\" IDProdotto ": 3, \" NomeProdotto \ ": \" Prodotto 3 \ "}, {\" IDProdotto ": 4, \" NomeProdotto \ ": \ "Prodotto 4 \"}, {\ "ProductID \": 5, \ "ProductName \": \ "Prodotto 5 \"}, {\ "IDProdotto": 6, \ "NomeProdotto \": \ "Prodotto 6 \"}, {\ "ID Prodotto \ ": 7, \" NomeProdotto \ ": \" Prodotto 7 \ "}, {\" IDProdotto ": 8, \" NomeProdotto \ ": \" Prodotto 8 \ "}, {\" IDProdotto ": 9 , \ "ProductName \": \ "Product 9 \"}, {\ "ProductID \": 10, \ "ProductName \": \ "Prodotto 10 \"}] "}

Ma sto cercando put below put

[{"ProductID": 1, "ProductName": "Prodotto 1"}, {"ID prodotto": 2, "ProductName": "Prodotto 2"}, {"ID prodotto": 3, "ProductName": "Product 3"}, {"ProductID": 4, "ProductName": "Product 4"}, {"ProductID": 5, "ProductName": "Product 5"}, {"ProductID": 6 , "ProductName": "Product 6"}, {"ProductID": 7, "ProductName": "Product 7"}, {"ProductID": 8, "ProductName": "Product 8"}, {"ProductID": 9, "ProductName": "P roduct 9 "}, {" ProductID ": 10," ProductName ":" 10" Prodotto}]

uno può dirmi che cosa è vero problema

Grazie

risposta

7

Prima c'è stato un cambiamento con ASP.NET 3.5 per motivi di sicurezza Microsoft ha aggiunto la "d" alla risposta. Di seguito è riportato un link da Dave Ward presso l'Encosia che parla di ciò che stai vedendo: A breaking change between versions of ASP.NET AJAX. Egli ha diversi post che parla di questo che può aiutare ulteriormente con l'elaborazione JSON e ASP.NET

+0

Grazie ewrankin per la gentile risposta ma il mio problema è che devo andare con asp.net 2.0 framework, quindi per favore mi suggerisci come posso ottenere questo. per favore se avete qualche altra opzione che per favore dimmi – Hiscal

+0

Mi dispiace, credo di non capire il tuo commento. Vuoi andare su ASP.NET 2.0? Perché in base alla risposta JSON che stai ricevendo stai utilizzando ASP.NET 3.5 a causa della "d" aggiuntiva che viene aggiunta. O stai chiedendo come lavorare con la "d" nella risposta che stai ricevendo. – ewrankin

+0

Ho lavorato con il tuo suggerimento ma continua a darmi lo stesso risultato con '\' indesiderato e non mi dà output come {"d": "[{" ProductID ": 1," ProductName ":" Prodotto 1 " }, {"ProductID": 2, "ProductName": "Product 2"}, {"ProductID": 3, "ProductName": "Product 3"}, {"ProductID": 4, "ProductName": "Prodotto 4 "}, {" ProductID ": 5," ProductName ":" Product 5 "}, {" ProductID ": 6," ProductName ":" Product 6 "}, {" ProductID ": 7," ProductName ":" Prodotto 7 "}, {" ProductID ": 8," ProductName ":" Prodotto 8 "}, {" ID prodotto ": 9," ProductName ":" Prodotto 9 "}, {" ID prodotto ": 10," Nome prodotto ":" Prodotto 10 "}]"} – Hiscal

0

In realtà, se si rimuove il

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

dal metodo, e si ritorna il jsonString che sei serializzato usando JavaScriptSerializer otterrai esattamente l'output che stavi cercando.

+2

Ho lo stesso problema, ma se rimuovo questo ResponseFormat, l'output viene avvolto con un nuovo tag:

-1

in servizio 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; 
    } 

in 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

Aspetta, cosa ????? – Dementic

+0

quando l'oggetto json passa .net all'app androi (con [ScriptMethod (ResponseFormat = ResponseFormat.Json)]) la risposta di Android ha

+0

Il tuo codice non è pertinente alla domanda posta. – Dementic

0

noti che u hanno le doppie virgolette accanto ur matrice nel tuo response.In questo modo u ritorno formato JSON non oggetto JSON da ur metodo web. Il formato json è una stringa. Pertanto è necessario utilizzare la funzione json.parse() per analizzare la stringa json su json object. Se non si desidera utilizzare parse fuction, è necessario rimuovere serialize nel proprio metodo web. ottieni un oggetto JSON.

+0

non è necessario aggiungere il metodo di risposta sul proprio metodo web. Se si inviano i parametri in jsonformat come questo" { 'prefisso': 'asd'} ", la rete restituirà la risposta in jsonobject. Altrimenti se invierai i tuoi dati in oggetti codificati o json come questo '' prefisso ':' asd '} senza virgolette. i dati arriveranno avvolto in xml. Quindi devi usare il formato di risposta in questo momento – Onr

Problemi correlati