我想构建自己的JSON,并让服务返回一个字符串,这里是代码
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
public string GetCurrentCart()
{
//Code ommited
string jsonClient = null;
var j = new { Content = response.Content, Display=response.Display, SubTotal=response.SubTotal};
var s = new JavaScriptSerializer();
jsonClient = s.Serialize(j);
return jsonClient;
}
Run Code Online (Sandbox Code Playgroud)
我得到的响应包含c#中字符串中的"用于创建".
以下是回复.
"{\"Content\":\"\\r\\n\\u003cdiv\\u003e\\r\\n\\u003cinput type=\\\"hidden\\\" name=\\\"__VIEWSTATE\\\" id=\\\"__VIEWSTATE\\\" value=\\\"\/wEPDwUBMA9kFgJmD2QWAmYPZBYGAgMPFgIeBFRleHQFKFlvdSBoYXZlIG5vIGl0ZW1zIGluIHlvdXIgc2hvcHBpbmcgY2FydC5kAgUPFgIeB1Zpc2libGVoZAIHDxQrAAIPFgIfAWhkZGQYAQUMY3RsMDEkbHZDYXJ0D2dkoWijqBUJaUxmDgFrkGdWUM0mLpgQmTOe8R8hc8bZco4=\\\" \/\\u003e\\r\\n\\u003c\/div\\u003e\\r\\n\\r\\n\\u003cdiv class=\\\"block block-shoppingcart\\\"\\u003e\\r\\n \\u003cdiv class=\\\"title\\\"\\u003e\\r\\n \\u003cspan\\u003eShopping Cart\\u003c\/span\\u003e\\r\\n \\u003c\/div\\u003e\\r\\n \\u003cdiv class=\\\"clear\\\"\\u003e\\r\\n \\u003c\/div\\u003e\\r\\n \\u003cdiv class=\\\"listbox\\\"\\u003e\\r\\n You have no items in your shopping cart.\\r\\n \\r\\n \\r\\n \\u003c\/div\\u003e\\r\\n\\u003c\/div\\u003e\\r\\n\",\"Display\":\"You have no items in your shopping cart.\",\"SubTotal\":null}" …
Run Code Online (Sandbox Code Playgroud) 这是我的困境.我正在使用RESTful ASP.NET服务,尝试使用以下格式返回JSON字符串的函数:
{"Test1Key":"Test1Value","Test2Key":"Test2Value","Test3Key":"Test3Value"}
Run Code Online (Sandbox Code Playgroud)
但我会以这种格式得到它:
[{"Key":"Test1Key","Value":"Test1Value"},
{"Key":"Test2Key","Value":"Test2Value"},
{"Key":"Test3Key","Value":"Test3Value"}]
Run Code Online (Sandbox Code Playgroud)
我的方法看起来像这样:
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public Dictionary<string, string> Test(String Token)
{
if (!IsAuthorized(Token))
return null;
if (!IsSecure(HttpContext.Current))
return null;
Dictionary<string, string> testresults = new Dictionary<string, string>();
testresults.Add("Test1Key", "Test1Value");
testresults.Add("Test2Key", "Test2Value");
testresults.Add("Test3Key", "Test3Value");
return testresults;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法只使用内置的ASP.NET工具摆脱那些"Key"和"Value"标签?(即,如果可以避免的话,我宁愿不使用JSON.NET)
非常感谢!:)
我不确定我错过了什么,我错过了什么.
我正在构建一个ASP.NET 2.0(在.Net 3.5框架上)Web应用程序,我正在包含一个Web服务.请注意,这不是 MVC项目.我希望公开一个返回JSON字符串的方法; 格式化以提供jqGrid jQuery插件.
这是我在我的服务中实现的初步测试方法:感谢(Phil Haack的MVC指南)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getData()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonData = new
{
total = 1, // we'll implement later
page = 1,
records = 3, // implement later
rows = new[]{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?", "yay"}},
new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?", "yay"}},
new …
Run Code Online (Sandbox Code Playgroud) 我在网上找到了几个针对WCF Web服务而不是ASP Web服务的解决方案.
目前,我正在收到一条JSON响应说:
{"d":[{"__type":"NetworkFuzzWebSvc.Sessions","BaseUri":"http://localbox","SessionId":"43b8716f-40ab-43bf-8311-575c2ecd2730}]}
Run Code Online (Sandbox Code Playgroud)
我需要它返回:
{"Sessions":["BaseUri":"http://localbox","SessionId":"43b8716f-40ab-43bf-8311-575c2ecd2730}]}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的Web服务代码的副本(NetFuzzWebSvc.asmx):
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
namespace NetworkFuzzWebSvc
{
public class Sessions
{
public string BaseUri;
public string SessionId;
}
/// <summary>
/// Summary description for NetFuzzJson
/// </summary>
[WebService(Namespace = "http://localbox")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class NetFuzzJson : WebService
{
List<Sessions> Sessions = new List<Sessions>
{
new Sessions{
BaseUri = "http://localbox/",
SessionId="43b8716f-40ab-43bf-8311-575c2ecd2730"
}
};
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Sessions> GetAllSessions()
{
return Sessions;
}
} …
Run Code Online (Sandbox Code Playgroud) 我需要将KnownType添加到下面的代码中,以便成功序列化.当我这样做时,生成的JSON如下:
JSON form of Adult with 1 child: {"age":42,"name":"John","children":[{"__type":"
Child:#TestJson","age":4,"name":"Jane","fingers":10}]}
Run Code Online (Sandbox Code Playgroud)
我怎么能不包含"__type":"Child:#TestJson"?我们在某些查询中返回了数百个这些元素,并且会添加额外的文本.
完整代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace TestJson
{
class Program
{
static void Main(string[] args)
{
Adult parent = new Adult {name = "John", age = 42};
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Adult));
ser.WriteObject(stream1, parent);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.Write("JSON form of Adult with no children: ");
Console.WriteLine(sr.ReadToEnd());
Child child = new Child { name …
Run Code Online (Sandbox Code Playgroud) 我试图确定如何__type
从我的JSON响应中排除asmx WebService.
我返回的类构造如下.
public class MyClassName
{
private string _item1 = string.Empty;
private string _item2 = string.Empty;
public string item1 = { get { return _item1; } set { _item1 = value; } }
public string item2 = { get { return _item2; } set { _item2 = value; } }
}
public class MyClassName_List : List<MyClassName>
{
public MyClassName_List() {}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个数据访问层和业务逻辑层,它返回一个填充的实例MyClassName_List
.我的WebMethod设置如下.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = …
Run Code Online (Sandbox Code Playgroud) 我正在使用网络服务获取有关路线里程的数据.然后我使用反序列化器来解析它.以下是JSON的外观:
[{"__type":"CalculateMilesReport:http:\/\/pcmiler.alk.com\/APIs\/v1.0","RouteID":null,"TMiles":445.5]
Run Code Online (Sandbox Code Playgroud)
有了这个回应,我有几个问题.为什么包装成集合,如何设置对象模型?它还抱怨特殊的__type属性.所以,我做了"黑客"和"准备"字符串:
// Cut off first and last charachters [] - they send objects as arrays
rawJSON = rawJSON.Substring(1, rawJSON.Length - 2);
// Hide "__type" attribute as it messes up serializer with namespace
rawJSON = rawJSON.Replace("__type", "type");
Run Code Online (Sandbox Code Playgroud)
然后一切都使用这个对象:
[DataContract]
public class PCMilerResponse
{
[DataMember(Name = "Errors", EmitDefaultValue = false)]
public PCMilerError[] Errors { get; set; }
[DataMember(Name = "TMiles", EmitDefaultValue = false)]
public decimal DrivingDistance { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在我修改了对Web服务的调用,我得到了以下响应
[
{"__type":"CalculateMilesReport:http:\/\/pcmiler.alk.com\/APIs\/v1.0","RouteID":null,"TMiles":445.5},
{"__type":"GeoTunnelReport:http:\/\/pcmiler.alk.com\/APIs\/v1.0","RouteID":null,"GeoTunnelPoints":
[{"Lat":"34.730466","Lon":"-92.247147"},{"Lat":"34.704863","Lon":"-92.29329"},{"Lat":"34.676312","Lon":"-92.364654"},{"Lat":"29.664271","Lon":"-95.236735"}]
}
]
Run Code Online (Sandbox Code Playgroud)
现在有理由为什么有数组和"__type".但我不确定如何编写对象来正确解析它.我想需要应用特殊属性,可能需要通用数组吗?有关如何正确反序列化的任何帮助?
PS我可以做更多的黑客攻击并替换那些使其成为对象的字符串,但我不知道是否有"正确"的方法来处理它.
.net c# json datacontractserializer datacontractjsonserializer