C# 如何在c中传递json对象#
我有这段代码,我创建了一个对象“person”,在方法“DoJson”中我声明了person并返回它,我在互联网上看到了一些例子,我也这样做了,但它不起作用C# 如何在c中传递json对象#,c#,json,C#,Json,我有这段代码,我创建了一个对象“person”,在方法“DoJson”中我声明了person并返回它,我在互联网上看到了一些例子,我也这样做了,但它不起作用 public class Service1 : System.Web.Services.WebService { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format. public string Do
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format.
public string DoJson()
{
var pers = new Person();
pers.edad = 1;
pers.nombre = "Name";
return pers;
}
}
public class Person
{
public int edad;
public string nombre;
}
您需要执行从对象到json的转换。见- 如果尚未添加对
System.Web
dll的引用,则可能需要添加对该dll的引用。将其更改为此
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "data/{id}")]
public Person GetData(string id)
{
// lookup person with the requested id
return new Person()
{
edad= Convert.ToInt32(edad),
nombre = "Leo Messi"
};
}
在您的例子中,我认为您只需要更改方法DoJson()的返回类型(在您以字符串形式返回对象时) 更改:
public string DoJson()
致:
然后当然,返回一个人
这是因为序列化程序需要知道它是个人,然后开始序列化。
public string DoJson(){
==>public person DoJson(){
什么具体不起作用?您可以描述它以及任何错误代码或异常详细信息。[ScriptMethod(ResponseFormat=ResponseFormat.Json]
是通知Web服务在发送到客户端之前将响应对象转换为json。因此不需要双重序列化。抱歉,我可能误解了您的需要。但是,使用Web服务也可以使用newtonsoft序列化程序。我个人的意见是,它工作得更好。
public string DoJson()
public Person DoJson()