javascript - 如何序列化此 JSON 对象?

标签 javascript asp.net ajax web-services jquery

我有一个网络服务接收一个 JSON 字符串作为参数。只有当我的 Web 方法的参数是通用类型“对象”时,我才能成功发送此消息。

我可以将这个通用对象序列化为字符串或自定义对象吗?我需要修改这个方法的参数类型吗?任何帮助都会很棒。

这是网络方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string StoreDataOut(object json)
{
   //serialization magic
}

这是传递给此 Web 方法的测试 JSON:

{
    "uid":"1234abcd",
    "application":"Application Name",
    "eventName":null,
    "clienttoken":"Test Client",
    "version":"1.0.0",
    "datetime":"1/1/2011 12:00 AM",
    "data":[
       {
           "id":"alpha_123",
            "question":"ronunciations in pre-classical times or in non-Attic dialects. For det",
            "answer":"nunciations "
        },
        {
        "id":"beta_456",
        "question":"official documents such as laws an",
        "answer":"or modif"
        },
        {
            "id":"gamma_789",
            "question":" maintained or modified slightly to fit Greek phonology; thus, ?",
            "answer":"iation of Attic"
        },
        {
            "id":"delta_098",
            "question":"econstructed pronunciation of Attic in the late 5th an",
            "answer":"unciation of "
        },
        {
            "id":"epsilon_076",
            "question":"erent stylistic variants, with the descending tail either going straight down o",
            "answer":"Whole bunch"
        },
        {
            "id":"zeta_054",
            "question":"rough breathing when it begins a word. Another diacritic use",
            "answer":"other dia"
        }
    ]
}

最佳答案

您需要一个如下所示的类并将其用作您的 web 方法中的类型而不是对象。

class JsonDTO
{

  public JsonDTO()
  {
    data = new List<data>();
  }
  public string uid {get; set;}
  public string application {get;set}
  public string eventName {get; set;}
  public string clienttoken {get;set}
  public string version {get;set;}
  public string @datetime {get; set;}
  public List<data> data {get; set;}



}

public class data
{
    public string id {get; set;}
    public string question {get; set;}
    public string answer {get; set;}
 }   

关于javascript - 如何序列化此 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111833/

相关文章:

asp.net - 在应用程序之间传递 Azure AD 身份验证

asp.net - 第一个项目的测试概念

ajax - 在 symfony 2.2 和 Ajax 上获取 POST 参数

php - 如何在AJAX中显示MYSQL错误?

javascript - 将 blob MIME 类型设置为 wav 仍然会导致 webM

javascript - 当函数被另一个函数调用时,函数无法正常工作

c# - 我的应用程序从 xml 文件中读取了过时的数据

javascript - 使用 AJAX 响应来最大限度地减少 SPA 中的进一步请求

javascript - 有什么方法可以扩展 javascript 的 array.sort() 方法以接受另一个参数?

javascript - Firebase Auth sendEmailVerification() 我收到错误,但仅限 Safari 浏览器