获取JSON数据并将其转换为c#中的类

时间:2013-12-03 17:43:21

标签: c# json

您好我想将一些json数据转换为c#类的实例:

例如,如果我有这个json代码:

"product": [                            
  { 
    "CarBrand": [ 
        "HippoCars", 
        "CondorTrucks", 
        "CheetahMotors"                  
    ], 
    "CarCategory": [ 
        "truck", 
        "car", 
        "MotorBike"

上课:

   public class Catalogue
{
    public List<Product> product { get; set; }
 public List<string> CarBrand { get; set; }
    public List<string> CarCategory { get; set; }
}

如何将JSON数据转换为c#类?

2 个答案:

答案 0 :(得分:3)

您可以尝试使用

var mydata = JsonConvert.DeserializeObject<Catalogue>(jsonString);

答案 1 :(得分:1)

首先,您的JSON不正确。这是正确的:

{ 
"product": [                              <--- double quotes
  { 
    "CarBrand": [ 
        "HippoCars", 
        "CondorTrucks", 
        "CheetahMotors"                   <---- no trailing comma
    ], 
    "CarCategory": [ 
        "truck", 
        "car", 
        "MotorBike"
    ]
  }                                       <----- closing object curly brackets
]                                         <----- closing array square brackets
}                                         <----- final }

然后你需要有两个类,而不是一个:

public class Catalogue
{
    public List<Product> product { get; set; }
}

public class Product
{
    public List<string> CarBrand { get; set; }
    public List<string> CarCategory { get; set; }
}

只有您可以使用Json.NET作为其他建议或

Catalogue catalogue = new JavaScriptSerializer().Deserialize<Catalogue>(jsonString);