ROSHITH
ROSHITH

Reputation: 5

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]

Upvotes: 0

Views: 500

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16059

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

Upvotes: 3

Yong Shun
Yong Shun

Reputation: 51260

You can achieve with DeserializeObject to List<Brand>. And use .Select() to get brand_id only.

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

string json = "[{\"brand_id\":\"112\"},{\"brand_id\":\"114\"},{\"brand_id\":\"14\"}]";
List<Brand> brands = JsonConvert.DeserializeObject<List<Brand>>(json);
List<string> brandIDs = brands.Select(x => x.Brand_Id).ToList();
public class Brand
{
    [JsonProperty("brand_id")]
    public string Brand_Id {get;set;}   
}

Sample program

Upvotes: 2

Related Questions