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

前端 未结 2 1942
旧巷少年郎
旧巷少年郎 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<T>(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<MyObjectType>(incomingString);
    
    0 讨论(0)
  • 2021-01-03 13:09

    JSON in the Hidden Field is a valid way to do it, as the data would then be posted to the server. You could then use the System.Web.Script.Serialization.JavaScriptSerializer component to deserialize the data (to a dictionary) and access the data that way. Not 100% sure hhow array data comes out of that process. THere are also other tools like JSON.NET too to parse JSON.

    Another way is via a web service call, but that doesn't go through the page lifecycle.

    HTH.

    0 讨论(0)
提交回复
热议问题