ASP.NET JSON Web服务响应格式

问题描述 投票:6回答:4

我编写了一个简单的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 \“:\”产品3 \“},{\” ProductID \“:4,\” ProductName \“:\”产品4 \“} ,{\“ ProductID \”:5,\“ ProductName \”:\“产品5 \”},{\“ ProductID \”:6,\“ ProductName \”:\“产品6 \”},{\“ ProductID \“:7,\” ProductName \“:\”产品7 \“},{\” ProductID \“:8,\” ProductName \“:\”产品8 \“},{\” ProductID \“: 9,\“ ProductName \”:\“产品9 \”},{\“ ProductID \”:10,\“ ProductName \”:\“产品10 \”}]“}]

但是我正在寻找下面的输出

[{“ ProductID”:1,“ ProductName”:“产品1”},{“ ProductID”:2,“ ProductName”:“产品2”},{“ ProductID”:3,“ ProductName”:“产品3“},{” ProductID“:4,” ProductName“:”产品4“},{” ProductID“:5,” ProductName“:”产品5“},{” ProductID“:6,” ProductName“:”产品6“},{”产品ID“:7,”产品名称“:”产品7“},{”产品ID“:8,”产品名称“:”产品8“},{”产品ID“:9,”产品名称“: “产品9”},{“产品ID”:10,“产品名称”:“产品10”}]

任何人都可以告诉我什么是实际问题

谢谢

service response json
4个回答
8
投票

首先,出于安全原因,ASP.NET 3.5进行了更改,Microsoft在响应中添加了“ d”。以下是Encosia的Dave Ward的链接,内容涉及您的见解:A breaking change between versions of ASP.NET AJAX。他有几篇关于此的文章,可以帮助您进一步处理JSON和ASP.NET


0
投票

实际上,如果您只是删除

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

从该方法,然后返回使用JavaScriptSerializer序列化的jsonString,您将确切地得到所需的输出。


0
投票

[注意,您在响应中在ur数组旁边有双引号。这样,您从ur web方法返回json格式而不是json对象。Json格式是字符串。因此,您必须使用json.parse()函数才能将json字符串解析为json对象。如果您不想使用解析功能,则必须在您的web方法中删除序列化。这样您将获得json对象。


-1
投票

。net Web服务中]

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

在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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.