2012-06-15 40 views
6

Tôi cần tạo một json tùy chỉnh cho thư viện the jit. Tôi có nên sử dụng thêm C# logic hoặc bằng cách nào đó để mở rộng JsonSerializer. Json nên như thế này ->JIT. Cách tốt nhất để tuần tự hóa thành json

var json = { 
    "children": [ 
{ 
    "children": [ 
    { 
     "children": [], 
     "data": { 
      "playcount": "276", 
      "$color": "#8E7032", 
      "image": "http://userserve-ak.last.fm/serve/300x300/11403219.jpg", 
      "$area": 276 
     }, 
     "id": "album-Thirteenth Step", 
     "name": "Thirteenth Step" 
    } 
}] 

}

+0

bạn đã thử này - http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx –

+1

vâng nhưng tôi cần thêm tùy chỉnh json – Alexandr

Trả lời

4

Sử dụng Json.Net

public void Test() 
{ 
    Node root = new Node(); 
    Node child = new Node(); 
    Data data = new Data() { Area = 276, Color = "#8E7032", PlayCount = "276", Image = "http://userserve-ak.last.fm/serve/300x300/11403219.jpg" }; 
    Node grandChild = new Node() { Id = "album-Thirteenth Step", Name = "Thirteenth Step", Data = data }; 

    root.Children.Add(child); 
    child.Children.Add(grandChild); 

    var json = JsonConvert.SerializeObject(
           root, 
           new JsonSerializerSettings() { 
            NullValueHandling= NullValueHandling.Ignore, 
            Formatting= Newtonsoft.Json.Formatting.Indented 
           }); 
} 

public class Node 
{ 
    [JsonProperty("children")] 
    public List<Node> Children = new List<Node>(); 

    [JsonProperty("data")] 
    public Data Data; 

    [JsonProperty("id")] 
    public string Id; 

    [JsonProperty("name")] 
    public string Name; 
} 

public class Data 
{ 
    [JsonProperty("playcount")] 
    public string PlayCount; 

    [JsonProperty("$color")] 
    public string Color; 

    [JsonProperty("image")] 
    public string Image; 

    [JsonProperty("$area")] 
    public int Area; 
} 
1

Có bạn mặc dù về Json.net?

http://json.codeplex.com/

Ít nhất bạn sẽ có một mức độ tốt của căn phòng tùy biến + a serializer tốt hơn

1

json - công cụ tốt nhất để làm việc với json

+1

Tại sao nó là "tốt nhất"? Bạn có thể cung cấp một số ngữ cảnh? Hoặc là tốt nhất cho * tất cả * trường hợp sử dụng? –

+0

@ EmilVikström theo trang web riêng của nó là ... – iwein

+0

iwein, Bạn đã tìm thấy trang web của riêng mình ở đâu? –

Các vấn đề liên quan