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]
CodePudding user response:
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"]);
If you already have model defined for the input string, then you can use DeserializeObject()
method which is explained by @YongShun
CodePudding user response:
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;}
}