2009-08-06 59 views
5

Tôi đã viết một dịch vụ web đơn giản mà có được danh sách sản phẩm trong JSONText đó là chuỗi đối tượng đang ServiceASP.NET JSON Web Service đáp ứng định dạng

Web dưới

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

bây giờ nó cho tôi resoponse như bên dưới:

{"d": "[{\" ProductID \ ": 1, \" Tên sản phẩm \ ": \" Sản phẩm 1 \ "}, {\" ProductID \ ": 2, \" ProductName \ ": \" Sản phẩm 2 \ "}, {\" ProductID \ ": 3, \" Tên sản phẩm \ ": \" Sản phẩm 3 \ "}, {\" ProductID \ ": 4, \" Tên sản phẩm \ ": \ "Sản phẩm 4 \"}, {\ "ProductID \": 5, \ "ProductName \": \ "Sản phẩm 5 \"}, {\ "ProductID \": 6, \ "Tên sản phẩm \": \ "Sản phẩm 6 \"}, {\ "ProductID \ ": 7, \" Tên sản phẩm \ ": \" Sản phẩm 7 \ "}, {\" ProductID \ ": 8, \" Tên sản phẩm \ ": \" Sản phẩm 8 \ "}, {\" ProductID \ ": 9 , \ "Tên sản phẩm \": \ "Sản phẩm 9 \"}, {\ "ProductID \": 10, \ "Tên sản phẩm \": \ "Sản phẩm 10 \"}] "}

Nhưng tôi đang tìm bên dưới ra đặt

[{"ProductID": 1, "ProductName": "Sản phẩm 1"}, {"ProductID": 2, "ProductName": "Sản phẩm 2"}, {"ProductID": 3, "ProductName": "Sản phẩm 3"}, {"ProductID": 4, "ProductName": "Sản phẩm 4"}, {"ProductID": 5, "ProductName": "Sản phẩm 5"}, {"ProductID": 6 , "ProductName": "Sản phẩm 6"}, {"ProductID": 7, "ProductName": "Sản phẩm 7"}, {"ProductID": 8, "ProductName": "Sản phẩm 8"}, {"ProductID": 9, "Tên sản phẩm": "P roduct 9 "}, {" ProductID ": 10," ProductName ":" Sản phẩm 10" }]

có thể bất kỳ một cho tôi biết vấn đề thực tế là những gì

Cảm ơn

Trả lời

7

Đầu tiên là một sự thay đổi với ASP.NET 3.5 vì lý do bảo mật Microsoft đã thêm "d" vào phản hồi. Dưới đây là một liên kết từ Dave Ward tại Encosia nói về những gì bạn nhìn thấy: A breaking change between versions of ASP.NET AJAX. Ông có nhiều bài viết nói về này có thể giúp bạn tiếp tục với JSON chế biến và ASP.NET

+0

Cảm ơn ewrankin vì bạn đã trả lời loại nhưng vấn đề của tôi là tôi phải đi với asp.net 2.0 framework vì vậy bạn vui lòng đề nghị tôi làm thế nào tôi có thể đạt được điều này. xin vui lòng nếu bạn có bất kỳ lựa chọn nào khác ngoài xin vui lòng cho tôi biết – Hiscal

+0

Tôi xin lỗi tôi đoán tôi không hiểu nhận xét của bạn. Bạn có muốn đi đến ASP.NET 2.0? Bởi vì dựa trên phản hồi JSON bạn đang nhận, bạn đang sử dụng ASP.NET 3.5 vì "d" bổ sung đang được thêm vào. Hay bạn đang hỏi cách làm việc với "d" trong câu trả lời bạn nhận được. – ewrankin

+0

Tôi đã làm việc với đề xuất của bạn nhưng vẫn cung cấp cho tôi cùng đặt với không mong muốn '\' và không cho tôi kết quả như {"d": "[{" ProductID ": 1," ProductName ":" Product 1 " }, {"ProductID": 2, "ProductName": "Sản phẩm 2"}, {"ProductID": 3, "ProductName": "Sản phẩm 3"}, {"ProductID": 4, "ProductName": "Sản phẩm 4 "}, {" ProductID ": 5," ProductName ":" Sản phẩm 5 "}, {" ProductID ": 6," ProductName ":" Sản phẩm 6 "}, {" ProductID ": 7," ProductName ":" Sản phẩm 7 "}, {" ProductID ": 8," ProductName ":" Sản phẩm 8 "}, {" ProductID ": 9," ProductName ":" Sản phẩm 9 "}, {" ProductID ": 10," ProductName ":" Sản phẩm 10 "}]"} – Hiscal

0

Trên thực tế, nếu bạn chỉ cần loại bỏ các

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

từ phương pháp này, và bạn trả lại jsonString rằng bạn tuần tự hóa bằng cách sử dụng JavaScriptSerializer bạn sẽ nhận được exactelly đầu ra mà bạn đang tìm kiếm.

+2

Tôi đang gặp vấn đề tương tự, nhưng nếu tôi xóa Phản hồi này, thì đầu ra được bao bọc bằng một thẻ mới:

-1

trong dịch vụ 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; 
    } 

trong android Thông báo

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

Chờ đã, Cái gì ????? – Dementic

+0

khi đối tượng json chuyển .net tới ứng dụng androi (với [ScriptMethod (ResponseFormat = ResponseFormat.Json)]) phản hồi từ android có

+0

Mã của bạn không liên quan đến câu hỏi được yêu cầu. – Dementic

0

rằng u có dấu ngoặc kép bên cạnh mảng ur trong response.In bạn theo cách này u trở lại định dạng json không json đối tượng từ ur phương thức web.Json định dạng là một chuỗi.Trước khi u phải sử dụng json.parse() chức năng để phân tích chuỗi json để json object.If u không muốn sử dụng phân tích fuction, u phải loại bỏ serialize trong phương pháp web.Thus ur u có một đối tượng json.

+0

u không phải thêm phương thức phản hồi trên phương thức web ur.If u gửi paremeters ur trong jsonformat như thế này" { 'tiền tố': 'asd'} ", net sẽ trả về phản hồi trong jsonobject.Otherwise nếu u gửi dữ liệu ur trong biểu mẫu mã hóa hoặc đối tượng json như thế này {'tiền tố': 'asd'} mà không có dấu ngoặc kép. Dữ liệu sẽ đến gói trong xml.So u phải sử dụng định dạng phản hồi trong thời gian này – Onr

Các vấn đề liên quan