Working with JSON on the Server-Side in ASP.NET and C#

前端 未结 2 1940
旧巷少年郎
旧巷少年郎 2021-01-03 12:52

I have an ASP.NET web form that is using JQuery on the client-side. I have a user interface that is building a collection of objects and storing them in JSON. With my client

2条回答
  •  离开以前
    2021-01-03 13:08

    How you send it to the server is up to you - a hidden field, an AJAX call, whatever you prefer. Once you've got the string on the server, you'll need 2 things:

    1. A C# server-side representation of that object
    2. A converter to go from JSON to that C# representation.

    Let's adjust your example a bit, because "myCollection" in your example is an object, not a collection. So we'll call it myObject. Secondly, we'll assume that "data" is an array of strings. It could be anything, but we'll keep it simple.

    var myObject = {
      data: ["string1","string2"]
    };
    

    We'll also assume you're using the DataContractJsonSerializer, so you can easily map the two different case-styles...JavaScript is typically camelCase, and C# is typically ProperCase. So, in C#, this would be:

    [DataContract(Name="myObjectType")]
    public class MyObjectType{
      [DataMember(Name="data")]
      public string[] Data { get; set; }
    }
    

    Now you have two representations of the same structure, one in c#, one in JavaScript. To convert from one to the other, we can use the built-in DataContractJsonSerializer, like this:

    public static T Deserialize(string json)
    {
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
          DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
          return (T)serializer.ReadObject(ms);
        }
    }
    

    ...resulting in a final call of:

    MyObjectType myObject = Deserialize(incomingString);
    

提交回复
热议问题