user7615935
user7615935

Reputation:

Convert System.Collections.GenericList'1 [Newtonsoft.Json.Linq.JToken] List to Json Array c#

I want to Convert System.Collections.GenericList'1 [Newtonsoft.Json.Linq.JToken] to JSON array.

Initially i had my JSON Array string stored in myData as below:

var myData = l.GetJsonData();

Now then i filtered my Json with the help of LINQ as below :

 var root = JToken.Parse(myData);
    var study_year = "2016/2017";
    var term = 2;var values = root.Where(t =>
 (int?)t["term"] == term && (string)t["study_year"] == study_year).ToList();

Now values is the one with sorted data but not in Json Format it shows System.Collections.GenericList'1[Newtonsoft.Json.Linq.JToken], how can i make it display the sorted data in Json Array string .

Upvotes: 2

Views: 4438

Answers (2)

Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 3990

Simply just add the following below:

 var values = root.Where(t =>
     (int?)t["term"] == term && (string)t["study_year"] == study_year).ToList();
    var filteredJson = JsonConvert.SerializeObject(values);

Upvotes: 0

Kevin Smith
Kevin Smith

Reputation: 14436

From the list create a JArray with the list as the constructor argument. Once you've got the JArray just call ToString().

    var root = JToken.Parse("[ {\"name\" : \"a\", value : 40 },{\"name\" : \"b\", value : 10 }, {\"name\" : \"c\", value : 25 }  ]");

    var filtered = root.Where(t => (int?)t["value"] > 15 ).ToList();

    var jArray = new JArray(filtered);

    Console.WriteLine(jArray.ToString());

The above will output the below

[
  {
    "name": "a",
    "value": 40
  },
  {
    "name": "c",
    "value": 25
  }
]

Upvotes: 1

Related Questions