Home > Back-end >  How to select the same property in a json array? ASP.NET Core
How to select the same property in a json array? ASP.NET Core

Time:11-25

I have this string:

{
   "timezone":"UTC",
   "serverTime":1669313639361,
   "symbols":[
      {
         "symbol":"ETHBTC",
         "status":"TRADING",
         "baseAsset":"ETH",
      },
      {
         "symbol":"LTCBTC",
         "status":"TRADING",
         "baseAsset":"LTC",
      }
]

I want to transform it into a json with only symbol properties like: ["ETHBTC", "LTCBTC"]

CodePudding user response:

You can parse your json and use LINQ

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

string[] symbols = JObject.Parse(json)["symbols"].Select(x => (string) x["symbol"]).ToArray();

UPDATE

if you want a json array

JArray symbolsArr = new JArray( JObject.Parse(json)["symbols"].Select(x => (string) x["symbol"]));

//or 

json = symbolsArr.ToString();

//or 

json= JsonConvert.SerializeObject(symbols);

By you don't need to convert a string array to json if you want to use it in API, you can just return an array, it will be automatically converted to json my MVC controller action

  • Related