Service ASP.NET JSON Web服务响应格式
我已经编写了一个简单的web服务,它在JSONText中获取产品列表,JSONText是字符串对象 Web服务代码如下所示Service ASP.NET JSON Web服务响应格式,service,response,json,Service,Response,Json,我已经编写了一个简单的web服务,它在JSONText中获取产品列表,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; usi
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;
}
}
使用系统;
使用System.Collections.Generic;
使用System.Web;
使用System.Web.Services;
使用System.Web.Script.Services;
使用System.Runtime.Serialization.Json;
使用System.IO;
使用系统文本;
///
///JsonWebService的摘要说明
///
[WebService(命名空间=”http://tempuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
公共类JsonWebService:System.Web.Services.WebService
{
公共JsonWebService(){
//如果使用设计的组件,请取消注释以下行
//初始化组件();
}
[网络方法]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
公共字符串GetProductsJson(字符串前缀)
{
列表产品=新列表();
if(prefix.Trim().Equals(string.Empty,StringComparison.OrdinalIgnoreCase))
{
products=ProductFacade.GetAllProducts();
}
其他的
{
products=ProductFacade.GetProducts(前缀);
}
//yourobject是要序列化为json的actula对象(可能是集合)
DataContractJsonSerializer serializer=新的DataContractJsonSerializer(products.GetType());
//创建一个内存流
MemoryStream ms=新的MemoryStream();
//将对象序列化到内存流
serializer.WriteObject(ms、products);
//将序列化对象转换为字符串
string jsonString=Encoding.Default.GetString(ms.ToArray());
//关闭内存流
Close女士();
返回jsonString;
}
}
现在它给了我如下的回复:
{“d”:“[{“ProductID\”:1,\“ProductName\”:“产品1\”,{“ProductID\”:2,\“ProductName\”:“产品2\”,{“ProductID\”:3,\“ProductName\”:“产品3\”,{“ProductID\”:4,\“ProductName\”:“产品4\”,{“ProductID\”,{“ProductID\”:“产品5\”,{“ProductName\”:“产品5\”,{“ProductID\”,{“ProductID\”:6,\\:“ProductID\”:“产品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”:产品7”{“ProductID”:8“:“Product 8”}{“ProductID:9,”ProductName:“Product 9”},{“ProductID:10,”ProductName:“Product 10”}]
谁能告诉我真正的问题是什么
谢谢首先,出于安全原因,ASP.NET 3.5发生了更改,Microsoft在响应中添加了“d”。下面是来自Encosia的Dave Ward的链接,介绍了您所看到的内容:
.他有几篇文章谈到了这一点,如果你删除了
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
从方法中,返回使用JavaScriptSerializer序列化的jsonString,您将获得所需的准确输出。在.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();
}
}
私有静态字符串转换器StreamToString(InputStream为)
{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
尝试
{
而((line=reader.readLine())!=null)
{
sb.追加(第+行“\n”);
}
}
捕获(IOE异常)
{
e、 printStackTrace();
}
最后
{
尝试
{
is.close();
}
捕获(IOE异常)
{
e、 printStackTrace();
}
}
使某人返回字符串();
}
私有void LoadJsonDataFromASPNET()
{
尝试
{
DefaultHttpClient httpclient=新的DefaultHttpClient();
HttpPostHttpPostRequest=newHttpPost(this.WSURL+“/WS.asmx/Android_DDD”);
JSONObject jsonObjSend=新的JSONObject();
jsonObjSend.put(“kullanickey”,“value_1”);
jsonObjSend.put(“硬粒”,“价值2”);
jsonObjSend.put(“PersonelKey”、“value_3”);
StringEntity se=新的StringEntity(jsonObjSend.toString());
httpPostRequest.setEntity(se);
setHeader(“接受”、“应用程序/json”);
setHeader(“内容类型”、“应用程序/json”);
//httpPostRequest.setHeader(“接受编码”、“gzip”);//仅当要使用gzip压缩时才设置此参数
HttpResponse response=(HttpResponse)httpclient.execute(httpPostRequest);
HttpEntity=response.getEntity();
如果(实体!=null)
{
InputStream instream=entity.getContent();
字符串结果字符串=convertStreamToString(流内);
流内关闭();
resultString=resultString.substring(6,resultString.length()-3);
resultString=新字符串(android.util.Base64.decode(resultString,0),“UTF-8”);
JSONObject对象=新的JSONObject(resultString);
String oDurum=object.getString(“状态”);
如果(oDurum.equals(“OK”))
{
JSONArray-JSONArray=newjsonarray(object.getString(“R”);
if(jsonArray.length()>0)
{
for(int i=0;i