6

我编写了一个简单的 Web 服务,它在 JSONText 中获取产品列表,它是字符串对象

Web服务代码如下

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

现在它给了我如下响应:

{"d":"[{\"ProductID\":1,\"ProductName\":\"产品 1\"},{\"ProductID\":2,\"ProductName\":\"产品 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\":\"Product 9\"},{\"ProductID\":10,\"ProductName\":\"Product 10\"}]"}

但我正在寻找下面的输出

[{"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":"Product 9"},{"ProductID":10,"ProductName":"Product 10"}]

谁能告诉我什么是实际问题

谢谢

4

4 回答 4

8

首先,出于安全原因,ASP.NET 3.5 发生了变化,Microsoft 在响应中添加了“d”。下面是来自 Encosia 的 Dave Ward 的链接,其中谈到了您所看到的内容: ASP.NET AJAX 版本之间的重大变化。他有几篇文章讨论了这一点,可以帮助您进一步处理 JSON 和 ASP.NET

于 2009-08-06T13:14:46.773 回答
0

实际上,如果你只是删除

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

从该方法中,您返回使用 JavaScriptSerializer 序列化的jsonString,您将获得您正在寻找的输出。

于 2010-05-27T22:03:40.383 回答
0

请注意,您在响应中的数组旁边有双引号。这样,您从您的 Web 方法返回 json 格式而不是 json 对象。Json 格式是一个字符串。因此,您必须使用 json.parse() 函数来解析 json字符串到 json 对象。如果你不想使用解析功能,你必须在你的 web 方法中删除序列化。这样你就得到了一个 json 对象。

于 2015-03-13T08:27:58.170 回答
-1

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

在安卓中

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();
    }
}
于 2013-10-07T20:06:50.143 回答