ASP.NET JSON Web 服务响应格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1238672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:18:27  来源:igfitidea点击:

ASP.NET JSON Web Service Response format

serviceresponsejson

提问by Hiscal

I have written one simple web service which get product list in JSONText which is string object

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

Web Service code is below

网络服务代码如下

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

now it give me resoponse like below :

现在它给了我如下的响应:

{"d":"[{\"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\"}]"}

{"d":"[{\"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\"}]"}

But i am looking for below out put

但我正在寻找低于输出

[{"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"}]

[{"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"}]

can any one tell me what is actual problem

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

Thanks

谢谢

回答by ewrankin

First there was a change with ASP.NET 3.5 for security reasons Microsoft added the "d" to the response. Below is a link from Dave Ward at the Encosia that talks about what your seeing: A breaking change between versions of ASP.NET AJAX. He has several posts that talks about this that can help you further with processing JSON and ASP.NET

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

回答by Onr

Notice that u have double quotes beside ur array in your response.In this way u return json format not json object from ur web method.Json format is a string.Therefore u have to use json.parse() function in order to parse json string to json object.If u dont want to use parse fuction,u have to remove serialize in ur web method.Thus u get a json object.

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

回答by Radu094

Actually, if you just remove the

实际上,如果您只是删除

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

from the method, and you return the jsonStringthat you serialized using the JavaScriptSerializer you will get exactelly the output that you were looking for.

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

回答by ismail uzunok

in .net web service

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