2014-01-06 36 views
-1

我需要如下所示的最终json格式,并且应该是动态的。如何在c中使用json.net创建json格式#

{ 
     "product_items" : 
     [ 
     { 
      "_at" : 1,     
      "product_id" : "999" 
     },  
     { 
      "_at" : 2, 
      "quantity" : 2.00 
     }, 
     { 
      "_delete_at" : 3  
     } 
     ] 
    } 

如何创建一个JSON格式如上在code._at场dynamic.sometimes它可能是2,有时可能是10.我不要有想法就在C#中动态生成的JSON。

class Test 
    { 
     public ProductItem[] product_items { get; set; } 


     class ProductItem 
     { 
      public int[] _at { get; set; } 
      public int[] _delete { get; set; } 
      public int[] quantity { get; set; } 
      public string[] product_id{get;set;} 
     } 
    } 

我已经创建了json的属性如上。

+1

请详细说明***代码。 _at字段是动态的。有时它可能是2,有时可能是10 *** – Satpal

+0

现在我创建了一个2 [_at]次的json,它会不断变化。 – Arjunan

+0

你的意思就像'{“_at”:1,“_ at”:2“,_at”:3}'。这将是一个无效的JSON – Satpal

回答

1

我使用Newtonsoft library

你的类应该看起来更像是这样的:

public class ProductItem 
{ 
    public int _at { get; set; } 
    public string product_id { get; set; } 
    public double? quantity { get; set; } 
    public int? _delete_at { get; set; } 
} 

public class ProductItemObject 
{ 
    public List<ProductItem> product_items { get; set; } 
} 

一个例子上连载:

List<ProductItem> list = new List<ProductItem>(); 
ProductItemObject o = new ProductItemObject { product_items = list }; 

var item1 = new ProductItem { _at = 1, product_id = "001" }; 
var item2 = new ProductItem { _at = 2, quantity = 2.00 }; 
var item3 = new ProductItem { _delete_at = 3 }; 

list.Add(item1); 
list.Add(item2); 
list.Add(item3); 


string json = JsonConvert.SerializeObject(o, Formatting.Indented); 

// json string : 
//   { 
// "product_items": [ 
// { 
//  "_at": 1, 
//  "product_id": "001", 
//  "quantity": null, 
//  "_delete_at": null 
// }, 
// { 
//  "_at": 2, 
//  "product_id": null, 
//  "quantity": 2.0, 
//  "_delete_at": null 
// }, 
// { 
//  "_at": 0, 
//  "product_id": null, 
//  "quantity": null, 
//  "_delete_at": 3 
// } 
// ] 
//} 

另一种完全的动力,得到U中相同的Json字符串没有任何型号:

var jsonObject = new JObject(); 
dynamic objectList = jsonObject; 

objectList.product_items = new JArray() as dynamic; 

dynamic item = new JObject(); 
item._at = 1; 
item.product_id = "999"; 
objectList.product_items.Add(item); 

item = new JObject(); 
item._at = 2; 
item.quantity = 2.00; 
objectList.product_items.Add(item); 

item = new JObject(); 
item._delete_at = 3; 
objectList.product_items.Add(item); 

string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject, Formatting.Indented); 
0

好吧,如果我正确地理解你,你只需要能够生成JSON,产品清单应该是动态的,也许匿名类则:

public class Products 
{ 
    public Products() 
    { 
     product_items = new List<dynamic>(); 
    } 
    public List<dynamic> product_items { get; set; } 
} 

products.product_items.Add(new { _at = 1, product_id = "999" });