如何将此JSON文件转换为自定义c#对象

时间:2017-04-15 19:43:37

标签: c# json

我试图创建一种方法将整个json文件转换为我的自定义数据类型,称为产品

{  
   "unique_image_url_prefixes":[  

 ],
 "products_and_categories":{  
  "Tops/Sweaters":[  
     {  
        "name":"Knit Stripe S/S Raglan Top",
        "id":302418,
        "image_url":"//d17ol771963kd3.cloudfront.net/129807/ca/_9UoFPZi8Zs.jpg",
        "image_url_hi":"//d17ol771963kd3.cloudfront.net/129807/rc/_9UoFPZi8Zs.jpg",
        "price":9900,
        "sale_price":0,
        "new_item":true,
        "position":10,
        "category_name":"Tops/Sweaters",
        "price_euro":11600,
        "sale_price_euro":0
     }
     ], 
  "Shirts":[  
     {  
        "name":"Supreme®/Comme des Garçons SHIRT® Eyes Rayon Shirt",
        "id":302426,
        "image_url":"//d17ol771963kd3.cloudfront.net/132067/ca/9O934PRlIcw.jpg",
        "image_url_hi":"//d17ol771963kd3.cloudfront.net/132067/rc/9O934PRlIcw.jpg",
        "price":25800,
        "sale_price":0,
        "new_item":true,
        "position":3,
        "category_name":"Shirts",
        "price_euro":29800,
        "sale_price_euro":0
     }
     ]
  }
}

这只显示整个来源所在文件的几个部分,PasteBin

所以我试图做的就是转换它的每一部分(它是产品/项目)

    {  
    "name":"Knit Stripe S/S Raglan Top",
    "id":302418,
    "image_url":"//d17ol771963kd3.cloudfront.net/129807/ca/_9UoFPZi8Zs.jpg",
    "image_url_hi":"//d17ol771963kd3.cloudfront.net/129807/rc/_9UoFPZi8Zs.jpg",
    "price":9900,
    "sale_price":0,
    "new_item":true,
    "position":10,
    "category_name":"Tops/Sweaters",
    "price_euro":11600,
    "sale_price_euro":0
    }

到我的名为Product

的自定义数据类型
    public Product(string id_p, string name_p, string image_url_p, string category_name_p)
    {
    id = id_p;
    name = name_p;
    image_url = image_url_p;
    category_name = category_name_p;       
    }

然后我尝试将这些值中的每一个与我的程序用户指定的值进行比较

     List<Product> products = JsonConvert.DeserializeObject<List<Product>>(JsonString);

     if (products == null) return null;
     foreach (var product in products)
     {
          //  ownerform.Log(product.name, 0);
          if (product.category_name == T.item.Category && product.name.ToLower().Contains(T.item.Keyword.ToLower()))
          {
              ownerform.Log(string.Format("Resolved Keyword! Item : {0}", product.name), T.TID);
              return new GetUrlResponse(true, product);
          }

      }

我现在正在做的事情不起作用,我真的无法找到它。

2 个答案:

答案 0 :(得分:0)

在C#中使用JSON的好方法是使用JSON.NET

你可以找到API Documentation from JSON.NET - 官方网站可以帮助你解决这个问题。

这是将整个JSON文件转换为自定义数据类型的示例... 例如:用户 这只是一个简单的例子,让您更好地理解解决方案。

  

{      “user”:{                   “名字”:“asdf”,                   “teamname”:“b”,                   “email”:“c”              }   }

所以c#看起来像:

public class User
{
    public User(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject["user"];
        name = (string) jUser["name"];
        teamname = (string) jUser["teamname"];
        email = (string) jUser["email"];
    }

    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
}

// Use
private void Run()
{
    string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c""}";
    User user = new User(json);

    Console.WriteLine("Name : " + user.name);
    Console.WriteLine("Teamname : " + user.teamname);
    Console.WriteLine("Email : " + user.email);

 }

答案 1 :(得分:0)

您获得的异常表明您的反序列化存在问题。

我无法分辨你实际做了什么,但如果你试图反序列化整个json对象(即整个文件),你应该明白它不包含Products列表,但是更复杂的类型'等级。因此,这一行失败了:

List<Product> products = JsonConvert.DeserializeObject<List<Product>>(JsonString);

我将列出两个选项,让你的事情发挥作用,选择你觉得更舒服的任何事情。

请注意,我将使用更简洁的json对象。另外,我已经为每个数组添加了另一个对象,以使事情变得更加真实(如在你的文件中)):

{
  "unique_image_url_prefixes": [],
  "products_and_categories": {
    "Tops": [
      {
        "name": "Top1",
        "id": "1"
      },
      {
        "name": "Top2",
        "id": "2"
      }
    ],
    "Shirts": [
      {
        "name": "Shirt1",
        "id": "3"
      },
      {
        "name": "Shirt2",
        "id": "4"
      }
    ]
  }
}

选项#1

构建类层次结构

转到链接到的post @CodingYoshi,并使用Visual Studio创建类层次结构。你将获得与以下层次结构非常相似的东西,不过我会更简洁:

public class Rootobject
{
    public object[] unique_image_url_prefixes { get; set; }
     public Products_And_Categories products_and_categories { get; set; }
}

public class Products_And_Categories
{
    public TopsSweaters[] TopsSweaters { get; set; }
    public Shirts[] Shirts { get; set; }
}

public class TopsSweaters
{
    public string name { get; set; }
    public int id { get; set; }
}

public class Shirts
{
    public string name { get; set; }
    public int id { get; set; }
}

<强> 反序列化

这是你反序列化字符串的方法:

string JsonString = @"{""unique_image_url_prefixes"":[],""products_and_categories"":{""TopsSweaters"":[{""name"":""Top1"",""id"":""1""},{""name"":""Top2"",""id"":""2""}],""Shirts"":[{""name"":""Shirt1"",""id"":""3""},{""name"":""Shirt2"",""id"":""4""}]}}"; 
Rootobject container = JsonConvert.DeserializeObject<Rootobject>(JsonString);

然后,您可以遍历TopsSweaters内的每个数组(Shirtscontainer.products_and_categories)。

选项#2

如果您想使用其他类层次结构(例如,您的Product类),则可以执行以下操作:

构建类层次结构

public class Product
{
    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("id")]
    public int id { get; set; }
}

// Choose either one of the following (they function the same):    
public class ProductsContainer1
{
    [JsonProperty("TopsSweaters")]
    public List<Product> ProductsList1 { get; set;}

    [JsonProperty("Shirts")]
    public List<Product> ProductsList2 { get; set;}
}

public class ProductsContainer2
{
    public List<Product> TopsSweaters { get; set; }
    public List<Product> Shirts { get; set; }
}

// Choose either one of the following (they function the same): 
public class Things1
{
    [JsonProperty("unique_image_url_prefixes")]
    public object[] Prefixes { get; set;}

    [JsonProperty("products_and_categories")]
    public ProductsContainer1 Products { get; set;}
}

public class Things2
{
    public object[] unique_image_url_prefixes { get; set;}
    public ProductsContainer2 products_and_categories { get; set;}
}

<强> 反序列化

反序列化如下:

string JsonString = @"{""unique_image_url_prefixes"":[],""products_and_categories"":{""TopsSweaters"":[{""name"":""Top1"",""id"":""1""},{""name"":""Top2"",""id"":""2""}],""Shirts"":[{""name"":""Shirt1"",""id"":""3""},{""name"":""Shirt2"",""id"":""4""}]}}"; 
// Use either one of the following: 
Things1 container1 = JsonConvert.DeserializeObject<Things1>(JsonString);
Things2 container2 = JsonConvert.DeserializeObject<Things2>(JsonString);