2013-05-28 63 views
7

Tôi có JSON chuỗi như sauLàm thế nào để loại bỏ thuộc tính cụ thể từ JSON chuỗi bằng C#

[{ 
     "attachments": [{ "comment": "communication", "comment_date_time": "2035826"} ], 
     "spent_hours": "4.00", 
     "description": ""  
    }, 
    { 
     "attachments": [], 
     "spent_hours": "4.00", 
     "description": ""  
    }] 

Làm thế nào tôi có thể loại bỏ các attachments thuộc tính từ JSON chuỗi sử dụng C#. Tôi đang sử dụng JSON.net.

+0

cố gắng sử dụng Newtonsoft.JSON để chuyển đổi JSON để NET đối tượng và sau đó bạn có thể loại bỏ nó một cách dễ dàng –

+1

thử này => http: //james.newtonking.com/pages/json-net.aspx –

+0

Tôi nghĩ bạn có thể làm như được mô tả trong http://stackoverflow.com/a/32153051 –

Trả lời

18

Sử dụng LINQ

var jArr = JArray.Parse(json); 

jArr.Descendants().OfType<JProperty>() 
        .Where(p => p.Name == "attachments") 
        .ToList() 
        .ForEach(att=>att.Remove()); 

var newJson = jArr.ToString(); 

hoặc sử dụng các lớp học vô danh

var anon = new[] { new{spent_hours="", description=""} }; 
var newJson = JsonConvert.SerializeObject(
         JsonConvert.DeserializeAnonymousType(json, anon)); 
+0

Nó hoạt động hoàn hảo (sử dụng LINQ) ... –

+1

@IrappaBisanakoppa rồi http://meta.stackexchange.com/questions/5234/how -does-accepting-an-answer-work – I4V

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