Benefits and drawbacks of generated C# classes for Json objects

房东的猫 提交于 2019-12-04 09:40:58

I assume you want to deserialize json string to c# object. I usually create C# object by myself, and use JsonConvert to deserialize json string.

class Program {
        static void Main(string[] args)
        {
                string json = @"
                {
                        ""street_address"":""My street address"",
                        ""city"":""My City"",
                        ""state_province"":""My State Province"",
                        ""zip_postal_code"":""My Zip Postal Code"",
                }";

                Address address = JsonConvert.DeserializeObject<Address>(json);
                Console.WriteLine("Street address: {0}", address.StreetAddress);
                Console.WriteLine("City: {0}", address.City);
                Console.WriteLine("State province: {0}", address.StateProvince);
                Console.WriteLine("Zip postal code: {0}", address.ZipPostalCode);
        }
}

public class Address {
        [JsonProperty("street_address")]
        public string StreetAddress { get; set; }

        [JsonProperty("city")]
        public string City { get; set; }

        [JsonProperty("state_province")]
        public string StateProvince { get; set; }

        [JsonProperty("zip_postal_code")]
        public string ZipPostalCode { get; set; }
}

If you know what kind of objects you will be returning, then look at using the System.Runtime.Serialization.Json namespace in the 4.0 Framework. It's much easier to use than JSON.NET. In fact, it's probably the easiest alternative available.

After including references to this namespace (and a using statement), you need to mark up your classes with the [DataContract] attribute and each property with the [DataMember] attribute. Then, you can use a generic routine like this one:

/// <summary>
/// 
/// Generic helper class to convert JSON text to in-memory objects
/// </summary>
/// <typeparam name="T">Type of class that the text represents</typeparam>
public class JSONHandler<T> where T : class, new()
{
    /// <summary>
    /// Convert a JSON string to an in-memory object of class T.
    /// The class T must be instantiable and not static.
    /// </summary>
    /// <param name="JSONString">JSON string describing the top level object</param>
    /// <returns>Object of class T (and any dependent objects)</returns>
    public T TextToJSON(string JSONString)
    {
        //check that we aren't passing in empty text
        if (String.IsNullOrEmpty(JSONString))
        {
            return null;
        }
        else
        {
            //create a new object
            T JSONObject = new T();
            //and create a new serializer for it
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            //create a memor stream around the text
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(JSONString));
            //do the conversion
            JSONObject = (T)ser.ReadObject(ms);
            //tidy up after ourselves
            ms.Close();
            //and we're done!
            return JSONObject;
        }
    }       
}

And that is all there is to it.

L.B

I never use class generators. When there are few classes, I code them manually. When a lot of classes are needed for deserialization process, I prefer to use dynamic object, and use it as here which makes the code more readable.

Here is an example usage of dynamic json

string json = @"{Users:[{Name:'name1',Id:1},{Name:'name2',Id:2}]}";
dynamic obj = JsonUtils.JsonObject.GetDynamicJsonObject(json);
foreach (var user in obj.Users)
{
    Console.WriteLine("{0} {1}", user.Name, user.Id);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!