2013-05-28 65 views
7

刪除特定的屬性我有JSON串如下如何從JSON字符串使用C#

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

我怎樣才能把用C#的JSON字符串attachments屬性。我正在使用JSON.net。

+0

嘗試使用Newtonsoft.JSON轉換JSON到.NET對象,然後你可以很容易地 –

+1

刪除它試試這個=> HTTP: //james.newtonking.com/pages/json-net.aspx –

+0

我認爲你可以像http://stackoverflow.com/a/32153051中所描述的那樣做 –

回答

18

使用LINQ

var jArr = JArray.Parse(json); 

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

var newJson = jArr.ToString(); 

或使用匿名類

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

它完美(使用linq)... –

+1

@IrappaBisanakoppa then http://meta.stackexchange.com/questions/5234/how -does接受-的回答工作 – I4V