2012-06-29 78 views
11

嗨,我有以下JSON响应,我如何将其转换为C#类对象转换成JSON对象类在C#

{ "err_code": "0", "org": "CGK", "des": "SIN", "flight_date": "20120719", 
"schedule": 
[ 
["W2-888","20120719","20120719","1200","1600","03h00m","737-200","0",[["K","9"],["F","9"],["L","9"],["M","9"],["N","9"],["P","9"],["C","9"],["O","9"]]], 
["W2-999","20120719","20120719","1800","2000","01h00m","MD-83","0",[["K","9"],["L","9"],["M","9"],["N","9"]]] 

] } 
+0

“抓”它??? !! ?? – Jamiec

+0

如果您使用的是MVC,则有很多功能可以支持该转换。您也可以查看此链接:http://msdn.microsoft.com/en-us/library/bb410770.aspx –

+0

此问题需要更多信息。 –

回答

21

首先创建一个类来表示你的JSON数据。

public class MyFlightDto 
{ 
    public string err_code { get; set; } 
    public string org { get; set; } 
    public string flight_date { get; set; } 
    // Fill the missing properties for your data 
} 

使用Newtonsoft JSON序列Deserialize a json string到它的相应的类对象。

var jsonInput = "{ org:'myOrg',des:'hello'}"; 
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput); 

或使用JavaScriptSerializer将其转换为一个类(不推荐作为newtonsoft JSON序列似乎有更好的表现)。

string jsonInput="have your valid json input here"; // 
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); 
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput) 

假设您想将其转换为Customer classe的实例。你的类应该看起来类似于JSON结构(属性)

+1

我无法为该json响应创建类 – Vishwajeet

33

我建议你使用JSON.NET。它是一个开源的库序列化和反序列化的C#对象转换成JSON和JSON对象到.NET对象......

序列化实例:

Product product = new Product(); 
product.Name = "Apple"; 
product.Expiry = new DateTime(2008, 12, 28); 
product.Price = 3.99M; 
product.Sizes = new string[] { "Small", "Medium", "Large" }; 

string json = JsonConvert.SerializeObject(product); 
//{ 
// "Name": "Apple", 
// "Expiry": new Date(1230422400000), 
// "Price": 3.99, 
// "Sizes": [ 
// "Small", 
// "Medium", 
// "Large" 
// ] 
//} 

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json); 

性能相较于其他JSON序列技术 enter image description here

+3

哇塔尔哈什么答案,+ 1它:) –

+0

@dotNetSoldier谢谢:) – Talha

+0

嗨,塔尔哈我的问题是我不能够建立一个类的数据结构持有这个JSON结果 – Vishwajeet

0

这将需要一个JSON字符串,并把它变成任何类指定

public static T ConvertJsonToClass<T>(this string json) 
    { 
     System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
     return serializer.Deserialize<T>(json); 
    } 
9

要创建一个JSON类掀起了字符串,复制字符串。

在Visual Sudio中,单击编辑>粘贴特殊>粘贴Json作为类。

+3

令人惊讶的是,每个人只是跳过这个答案。 Upvoted。 –

+1

是的,我认为这是当时所要求的。这在VS2012中是一种迂回的事情(请参阅https://topicoverflow.com/)。com/questions/18526659/how-to-show-the-paste-json-class-in-visual-studio-2012-click-on-paste)现在在VS2017中,非常简单。 –