为Json对象生成C#类的优缺点

为Json对象生成C#类的优缺点,c#,asp.net,json,serialization,code-generation,C#,Asp.net,Json,Serialization,Code Generation,我有示例Json,需要将其序列化为C#对象。我决定利用这个图书馆。我还需要有C#类来表示这个Json。可以使用创建类。我们有两个选择。“创建属性”和生成的类如下所示: public class Address { private JObject __jobject; public Address(JObject obj) { this.__jobject = obj; } public string street_address {

我有示例Json,需要将其序列化为C#对象。我决定利用这个图书馆。我还需要有C#类来表示这个Json。可以使用创建类。我们有两个选择。“创建属性”和生成的类如下所示:

public class Address
{
    private JObject __jobject;
    public Address(JObject obj)
    {
        this.__jobject = obj;
    }
    public string street_address
    {
        get
        {
            return JsonClassHelper.ReadString(JsonClassHelper.GetJToken<JValue>(__jobject, "street_address"));
        }
    }
    public string city
    {
        get
        {
            return JsonClassHelper.ReadString(JsonClassHelper.GetJToken<JValue>(__jobject, "city"));
        }
    }
    public string state_province
    {
        get
        {
            return JsonClassHelper.ReadString(JsonClassHelper.GetJToken<JValue>(__jobject, "state_province"));
        }
    }
    public string zip_postal_code
    {
        get
        {
            return JsonClassHelper.ReadString(JsonClassHelper.GetJToken<JValue>(__jobject, "zip_postal_code"));
        }
    }
}
另一种方法是使用在线转换器,类看起来像

public class Address
{

    public Address(JObject obj)
    {
       this.street_address = JsonClassHelper.ReadString(JsonClassHelper.GetJToken<JValue>(obj, "street_address"));
       this.city = JsonClassHelper.ReadString(JsonClassHelper.GetJToken<JValue>(obj, "city"));
       this.state_province = JsonClassHelper.ReadString(JsonClassHelper.GetJToken<JValue>(obj, "state_province"));
       this.zip_postal_code = JsonClassHelper.ReadString(JsonClassHelper.GetJToken<JValue>(obj, "zip_postal_code"));
    }

    public readonly string street_address;
    public readonly string city;
    public readonly string state_province;
    public readonly string zip_postal_code;
}
public class Address
{
    public string street_address { get; set; }
    public string city { get; set; }
    public string state_province { get; set; }
    public string zip_postal_code { get; set; }
}
JsonSerializer可以处理这个类。

我的问题是generator更喜欢使用什么类,以及使用每种生成的类的优点和缺点是什么?

谢谢您的建议。

我假设您想将json字符串反序列化为c#对象。我通常自己创建C#对象,并使用
JsonConvert
对json字符串进行反序列化

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; }
}
类程序{
静态void Main(字符串[]参数)
{
字符串json=@”
{
“街道地址”:“我的街道地址”,
“城市”:“我的城市”,
“州/省”:“我的州/省”,
“邮政编码”:“我的邮政编码”,
}";
Address Address=JsonConvert.DeserializeObject(json);
Console.WriteLine(“街道地址:{0}”,address.StreetAddress);
Console.WriteLine(“City:{0}”,address.City);
Console.WriteLine(“州省:{0}”,地址.StateProvince);
WriteLine(“邮政编码:{0}”,地址.ZipPostalCode);
}
}
公共课堂演讲{
[JsonProperty(“街道地址”)]
公共字符串StreetAddress{get;set;}
[JsonProperty(“城市”)]
公共字符串City{get;set;}
[JsonProperty(“州/省”)]
公共字符串StateProvince{get;set;}
[JsonProperty(“邮政编码”)]
public string ZipPostalCode{get;set;}
}

我从不使用类生成器。当类很少时,我手动编写它们。当反序列化过程需要很多类时,我更喜欢使用
dynamic
对象,并将其用作使代码更具可读性的对象

下面是一个使用


如果您知道将返回哪种类型的对象,请查看在4.0框架中使用System.Runtime.Serialization.Json命名空间。它比JSON.NET更易于使用。事实上,这可能是最简单的选择

在包含对该名称空间的引用(以及使用语句的之后,需要使用[DataContract]属性标记类,并使用[DataMember]属性标记每个属性。然后,您可以使用如下通用例程:

/// <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;
        }
    }       
}
//
/// 
///将JSON文本转换为内存中对象的通用帮助器类
/// 
///文本表示的类的类型
公共类JSONHandler,其中T:class,new()
{
/// 
///将JSON字符串转换为类T的内存中对象。
///类T必须是可实例化的,而不是静态的。
/// 
///描述顶级对象的JSON字符串
///T类对象(以及任何从属对象)
公共T TextToJSON(字符串JSONString)
{
//检查我们没有传递空文本
if(String.IsNullOrEmpty(JSONString))
{
返回null;
}
其他的
{
//创建一个新对象
T JSONObject=newt();
//并为其创建一个新的序列化程序
DataContractJsonSerializer ser=新的DataContractJsonSerializer(类型(T));
//围绕文本创建一个memor流
System.IO.MemoryStream ms=new System.IO.MemoryStream(Encoding.Unicode.GetBytes(JSONString));
//进行转换
JSONObject=(T)ser.ReadObject(ms);
//收拾
Close女士();
//我们完了!
返回JSONObject;
}
}       
}

这就是全部

谢谢你的建议。我同意您的观点,即使用DataContractJsonSerializer更容易,但它也有更多的限制。e、 g.日期和时间字段的格式。Json.Net支持它可以成功解析的更广泛的格式。这一点很重要,因为该服务将为第三方.L.B发布,但这种方法缺乏编译时验证。还是我遗漏了什么?
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; }
}
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);
}
/// <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;
        }
    }       
}