2009-08-06 15 views
5

Pisałem jedną prostą usługę internetową, która uzyskać listę produktów w JSONText który jest przedmiotem ciągJSON ASP.NET Web Service Response Format

Web Service jest kod poniżej

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

teraz daj mi resoponse jak poniżej:

{"d": "[{\" ID produktu \ ": 1, \" Nazwa produktu \ ": \" Produkt 1 \ "}, {\" Identyfikator produktu \ ": 2, \" Nazwa produktu \ ": \" Produkt 2 \ "}, {\" ID produktu \ ": 3, \" Nazwa produktu \ ": \" Produkt 3 \ "}, {\" ID produktu \ ": 4, \" Nazwa produktu \ ": \ "Produkt 4 \"}, {\ "ID produktu \": 5, \ "Nazwa produktu \": \ "Produkt 5 \"}, {\ "ID produktu \": 6, \ "Nazwa produktu \": \ "Produkt 6 \"}, {\ "ID produktu" \ ": 7, \" NazwaProduktu \ ": \" Produkt 7 \ "}, {\" Identyfikator produktu \ ": 8, \" NazwaProduktu \ ": \" Produkt 8 \ "}, {\" Identyfikator produktu \ ": 9 , \ "ProductName \": \ "Product 9 \"}, {\ "ProductID \": 10, \ "ProductName \": \ "Product 10 \"}] "}

Ale szukam poniżej umieścić

[{"ProductID": 1, "ProductName": "Product 1"}, {"ProductID": 2, "ProductName": "Product 2"}, {"ProductID": 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" Produkt}]

może ktoś mi powiedzieć jaki jest rzeczywisty problem

Dzięki

Odpowiedz

7

Najpierw nastąpiła zmiana z ASP.NET 3.5 ze względów bezpieczeństwa Firma Microsoft dodała odpowiedź "d". Poniżej znajduje się link od Dave Warda na Encosia, który mówi o tym, co widzisz: A breaking change between versions of ASP.NET AJAX. Ma kilka stanowisk, które mówi o tym, że może dodatkowo pomóc w JSON przetwarzania i ASP.NET

+0

Dzięki ewrankin dla ciebie rodzaju odpowiedź ale mój problem jest muszę iść z asp.net 2.0 ramy, więc proszę o sugestię, jak mogę to osiągnąć. proszę, jeśli masz jakąś inną opcję, proszę powiedz mi – Hiscal

+0

Przepraszam, myślę, że nie rozumiem twojego komentarza. Czy chcesz przejść do ASP.NET 2.0? Ponieważ na podstawie otrzymanej odpowiedzi JSON używasz ASP.NET 3.5 ze względu na dodatkowe "d", które jest dodawane. Czy też pytasz, jak pracować z "d" w odpowiedzi, którą otrzymujesz. – ewrankin

+0

Mam pracę z twoją sugestią, ale nadal daje mi to samo out z niechcianym "\" i nie daje mi wyników takich jak {"d": "[{" ProductID ": 1," ProductName ":" Produkt 1 " }, {"ProductID": 2, "ProductName": "Product 2"}, {"ProductID": 3, "ProductName": "Product 3"}, {"ProductID": 4, "ProductName": "Produkt 4 "}, {" ProductID ": 5," ProductName ":" Product 5 "}, {" ProductID ": 6," ProductName ":" Product 6 "}, {" ProductID ": 7," ProductName ":" Produkt 7 "}, {" ProductID ": 8," ProductName ":" Product 8 "}, {" ProductID ": 9," ProductName ":" Product 9 "}, {" ProductID ": 10," ProductName ":" Produkt 10 "}]"} – Hiscal

0

Właściwie, jeśli po prostu usunąć

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

od metody, a zwracają jsonString że serializowałeś za pomocą JavaScriptSerializer, a otrzymasz dokładnie to, czego szukałeś.

+2

Mam ten sam problem, ale jeśli usunę ten ResponseFormat, wynik jest zawijany z nowym znacznikiem:

-1

w .NET usługi internetowej

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

w 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

Czekaj, co ????? – Dementic

+0

, gdy obiekt json przechodzi .net do aplikacji androi (z [ScriptMethod (ResponseFormat = ResponseFormat.Json)]) odpowiedź od Androida ma

+0

Twój kod nie jest odpowiedni do zadanego pytania. – Dementic

0

Zauważ, że u mają podwójne cudzysłowy obok ur tablicy w response.In ten sposób u powrotu formacie JSON nie json obiekt z Ur web metoda.Json format jest ciągiem.Dlatego musisz użyć funkcji json.parse(), aby parsować ciąg json do obiektu json.Jeśli nie chcesz korzystać z funkcji parse, musisz usunąć serializować w metodzie internetowej.Thus dostajesz obiekt json.

+0

nie musisz dodawać metody odpowiedzi na ur web method.Jeśli wysyłasz ur paremeters w jsonformat w ten sposób" { "prefiks": "asd"} ", net zwróci odpowiedź w jsonobject.Other, jeśli wyślesz dane w zakodowanym formularzu lub obiekcie json takim jak ten {'prefix': 'asd'} bez podwójnych cudzysłowów. Dane nadejdą opakowane w xml. W tym czasie musisz użyć formatu odpowiedzi – Onr