如何序列化这个JSON对象?

时间:2022-05-15 04:45:12

I have a web service that receives a JSON string as a parameter. I have only been able to successfully send this when my web method's parameter is a generic type 'object'.

我有一个web服务,它接收JSON字符串作为参数。只有当我的web方法的参数是泛型类型“对象”时,我才能够成功地发送它。

Can I serialize this generic object to a string or a custom object? Do I need to modify the parameter type of this method? Any help would be awesome.

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

Here is the web method:

以下是web方法:

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

This is the test JSON that is being passed to this web method:

这是传递给这个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"
        }
    ]
}

2 个解决方案

#1


2  

You need a class as follows and use that as the type in your webmethod instead of object.

您需要如下所示的类,并将其用作webmethod中的类型,而不是对象。

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

#2


2  

You should be able to have the .Net framework correctly serialise most objects so your web method signature looks like this:

您应该能够让.Net框架正确地序列化大多数对象,因此您的web方法签名如下:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string StoreDataOut(MyClass input);

But I've found that certain objects it has probelms with, and so my fallback method is to accept a string instead (which will be the serialised JSON), and deserialise it myself either using the JavaScriptSerializer class or a JSON serialisation library like Json.Net.

但是我发现它有一些对象,所以我的回退方法是接受一个字符串(它将是序列化的JSON),并使用JavaScriptSerializer类或Json.Net之类的JSON序列化库对它进行反序列化。

This is an example of deserialising an object using the JavaScriptSerializer class where I separate the "actual" method out with a wrapper method that handles the deserialistion for us:

这是使用JavaScriptSerializer类对一个对象进行反序列化的一个例子,在这个类中,我将“实际”方法与为我们处理反序列化的包装器方法分离出来:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string StoreDataOut(string input)
{
    var serialiser = new JavaScriptSerializer();
    MyClass deserialisedInput = serialiser.Deserialize<MyClass>(input);
    return (StoreDataOutImpl deserialisedInput);
}

private string StoreDataOutImpl(MyClass input);

This gives you the flexibility of being able to control the serialisation using JavaScriptConverters or using a completely different library (e.g. Json.Net).

这使您能够灵活地使用javascriptconverter或使用完全不同的库(例如Json.Net)控制序列化。

This will require that you have a class MyClass that is correctly formatted to recieve the input JSON. If you don't then you can can just get the serialiser to output a dictionary which will contain key - value pairs corresponding to the properties of the serialised JSON object:

这将要求您拥有一个正确格式化以接收输入JSON的MyClass类。如果没有,那么可以让serialiser输出一个字典,该字典将包含与序列化JSON对象的属性相对应的键-值对:

var deserialisedInput = (Dictionary<string, object>)serialiser.DeserializeObject(input);

#1


2  

You need a class as follows and use that as the type in your webmethod instead of object.

您需要如下所示的类,并将其用作webmethod中的类型,而不是对象。

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

#2


2  

You should be able to have the .Net framework correctly serialise most objects so your web method signature looks like this:

您应该能够让.Net框架正确地序列化大多数对象,因此您的web方法签名如下:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string StoreDataOut(MyClass input);

But I've found that certain objects it has probelms with, and so my fallback method is to accept a string instead (which will be the serialised JSON), and deserialise it myself either using the JavaScriptSerializer class or a JSON serialisation library like Json.Net.

但是我发现它有一些对象,所以我的回退方法是接受一个字符串(它将是序列化的JSON),并使用JavaScriptSerializer类或Json.Net之类的JSON序列化库对它进行反序列化。

This is an example of deserialising an object using the JavaScriptSerializer class where I separate the "actual" method out with a wrapper method that handles the deserialistion for us:

这是使用JavaScriptSerializer类对一个对象进行反序列化的一个例子,在这个类中,我将“实际”方法与为我们处理反序列化的包装器方法分离出来:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string StoreDataOut(string input)
{
    var serialiser = new JavaScriptSerializer();
    MyClass deserialisedInput = serialiser.Deserialize<MyClass>(input);
    return (StoreDataOutImpl deserialisedInput);
}

private string StoreDataOutImpl(MyClass input);

This gives you the flexibility of being able to control the serialisation using JavaScriptConverters or using a completely different library (e.g. Json.Net).

这使您能够灵活地使用javascriptconverter或使用完全不同的库(例如Json.Net)控制序列化。

This will require that you have a class MyClass that is correctly formatted to recieve the input JSON. If you don't then you can can just get the serialiser to output a dictionary which will contain key - value pairs corresponding to the properties of the serialised JSON object:

这将要求您拥有一个正确格式化以接收输入JSON的MyClass类。如果没有,那么可以让serialiser输出一个字典,该字典将包含与序列化JSON对象的属性相对应的键-值对:

var deserialisedInput = (Dictionary<string, object>)serialiser.DeserializeObject(input);