Search code examples
c#jsonjson.netdeserialization

String to comma separated array using Newtonsoft


I have an input string like

[{"brand_id":"112"},{"brand_id":"114"},{"brand_id":"14"}]

and I want to convert the string to a format like this using Newtonsoft.

[112,114,14]

Solution

  • Parse input string to JArray, then use .Select() to get value of particular key(in Your case it is brand_id)

    using System.Linq;
    using Newtonsoft.Json.Linq;
    ...
    //Input string 
    string json = @"[{'brand_id':'112'},{'brand_id':'114'},{'brand_id':'14'}]"; 
    //Convert input string to JArray
    JArray jArray = JArray.Parse(json);
    //Select only specific field
    var brandIds = jArray.Select(x => x["brand_id"]);
    

    Try online: C# fiddle


    If you already have model defined for the input string, then you can use DeserializeObject() method which is explained by @YongShun