Related
How to query some json to select a specific property?
EX: If I have Json obj like this :
[
{
"grd_symbol":"A+",
"count":21.23,
"code":4,
"name":"X",
"batch_no":760
},
{
"grd_symbol":"A ",
"count":11.93,
"code":4,
"name":"X",
"batch_no":760
},
{
"grd_symbol":"A-",
"count":8.49,
"code":4,
"name":"X",
"batch_no":760
}
]
This's the output of :
string JsonObj = Converter.ConvertDataTabletoString(DT);
public static string ConvertDataTabletoString(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
Now I want to get the count only,The result will be like this:
[21.23,11.93,8.49]
Take a look at Newtonsoft.JSON.
Using this, we can create an object to match the json string:
public class MyCustomObject
{
[JsonProperty("grd_symbol")] public string GridSymbol {get; set;}
[JsonProperty("count")] public double Count {get; set;}
[JsonProperty("code")] public int Code {get; set;}
[JsonProperty("name")] public string Name {get; set;}
[JsonProperty("batch_no")] public int BatchNumber {get; set;}
}
Then you can deserialize your json using the library mentioned above:
var myData = JsonConvert.DeserializeObject<MyCustomObject[]>(jsonString);
And then, since you want an array of the counts, you can use LINQ to get them using Select:
var countArray = myData.Select(x => x.Count);
And of course, if you want to output this as a string, you can just serialize it again:
var countString = JsonConvert.SerializeObject(countArray);
You don't even have to to deserialise all property to select just one you can simple omit the unwanted one in the calss definition so they will be ignored.
Using :
public class SimplifyRootObject
{
public double count { get; set; }
}
Instead of :
public class RootObject
{
public string grd_symbol { get; set; }
public double count { get; set; }
public int code { get; set; }
public string name { get; set; }
public int batch_no { get; set; }
}
Then a simple string.Join() to add the comma and there you are.
$"[{string.Join("_separator_", myListOfDouble)}]"
MCVE:
public static void Main(string[] args)
{
string input = #"[
{
""grd_symbol"":""A+"",
""count"":21.23,
""code"":4,
""name"":""X"",
""batch_no"":760
},
{
""grd_symbol"":""A "",
""count"":11.93,
""code"":4,
""name"":""X"",
""batch_no"":760
},
{
""grd_symbol"":""A-"",
""count"":8.49,
""code"":4,
""name"":""X"",
""batch_no"":760
}
]";
// Deserialize All, select the wanted.
var m = JsonConvert.DeserializeObject<List<RootObject>>(input);
var result = m.Select(x=> x.count);
Console.WriteLine("["+string.Join(", ", result)+"]");
// Deserialize only one, select it.
var m2 = JsonConvert.DeserializeObject<List<SimplifyRootObject>>(input);
var result2 = m.Select(x=> x.count);
Console.WriteLine("["+string.Join(", ", result2)+"]");
}
}
https://rextester.com/PFJZN10272;
The label of your topic is "how to do a projection on json string" and you're telling us that you already have a DataTable that you want to convert into a string.
The code you gave us though means "I want to serialize my datatable into a JSON string".
In the end, what do you even need ? An array of string ? a string ? a json object ?
If it's a string, i would suggest you to override the ToString() method of DataTable to get the format you want i.e [number1, number2, number3] by fetching the datatable and returning a STRING and not a JSON.
Edit. #ThePerplexedOne has answered the question, i think.
I trying to get the id and email list from the JSON. How can i achieve this?
My JSON string is
{
"name":"name1",
"username":"name1",
"id":505,
"state":"active",
"email":"name1#mail.com",
},
{
"name":"name2",
"username":"name2",
"id":504,
"state":"active",
"email":"name2#mail.com",
}
My code is
Dictionary<string, string> engineers = new Dictionary<string, string>();
using (StreamReader r = new StreamReader(#"D:\project\Gitlap\EngineerEmail\jsonlist5.json"))
{
using (JsonTextReader reader = new JsonTextReader(r))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
string id = o2["id"].ToString();
string email = o2["email"].ToString();
engineers.Add(email, id);
}
}
class UserItems
{
public string id { get; set; }
public string email { get; set; }
}
I can able to get the first person`s mail ID and ID details. I need to iterate this JSON and get all the mail ID and ID.
I don`t know that how to iterate this JSON. I tried some method from the internet but that was not succeeded.
How can I do?
First thing is your JSON input is not valid json, you need to fix it. There are two issues in it. Its not collection of json objects and comma is missing between two objects.
Valid json should look like below.
[{
"name":"name1",
"username":"name1",
"id":505,
"state":"active",
"email":"name1#mail.com",
},
{
"name":"name2",
"username":"name2",
"id":504,
"state":"active",
"email":"name2#mail.com",
}]
Now define a c# class representing your json object.
public class User
{
public string name { get; set; }
public string username { get; set; }
public int id { get; set; }
public string state { get; set; }
public string email { get; set; }
}
Use JSON.Net library to deserialize it as shown below.
private void button1_Click(object sender, EventArgs e)
{
if(File.Exists("json1.json"))
{
string inputJSON = File.ReadAllText("json1.json");
if(!string.IsNullOrWhiteSpace(inputJSON))
{
var userList = JsonConvert.DeserializeObject<List<User>>(inputJSON);
}
}
}
JObject o2 = (JObject)JToken.ReadFrom(reader);
foreach(var obj in o2)
{
string id = obj["id"].ToString();
string Email= obj["Email"].ToString();
engineers.Add(email, id);
}
I would recommend using the Json.NET NuGet package to accomplish this.
Firstly, create a model to represent your JSON data. Typically I would capitalize the first letter of the property names here, but to keep it consistent with the JSON, they are lower case.
public class UserData
{
public string name { get; set; }
public string username { get; set; }
public int id { get; set; }
public string state { get; set; }
public string email { get; set; }
}
You will need to add a using for Json.NET
using Newtonsoft.Json;
Finally, you can load, and deserialize your data into a strongly typed list, which you can then use to populate your engineers dictionary.
string datapath = #"D:\project\Gitlap\EngineerEmail\jsonlist5.json";
Dictionary<string, string> engineers = new Dictionary<string, string>();
List<UserData> data = new List<UserData>();
using (StreamReader r = new StreamReader(datapath))
{
string json = r.ReadToEnd();
data = JsonConvert.DeserializeObject<List<UserData>>(json);
data.ForEach(engineer => engineers.Add(engineer.email, engineer.id.ToString()));
}
As mentioned in another answer, your JSON is also badly formed. This will need correcting before it will deserialize correctly. We just need to add a comma to separate the two objects, and wrap them both in a JSON array, with []
[
{
"name":"name1",
"username":"name1",
"id":505,
"state":"active",
"email":"name1#mail.com"
},
{
"name":"name2",
"username":"name2",
"id":504,
"state":"active",
"email":"name2#mail.com"
}
]
Improvements
As your Id field is an integer, it would be better to change your dictionary from
Dictionary<string, string> engineers = new Dictionary<string, string>();
into
Dictionary<string, int> engineers = new Dictionary<int, string>();
You will then be able to simplify your ForEach query slightly. The ForEach can also be moved outside of the using() block.
data.ForEach(engineer =>
engineers.Add(engineer.email, engineer.id));
Improved solution
This includes the improvements above, I've used var for brevity.
var datapath = #"D:\project\Gitlap\EngineerEmail\jsonlist5.json";
var engineers = new Dictionary<string, int>();
var data = new List<UserData>();
using (var r = new StreamReader(datapath))
{
var json = r.ReadToEnd();
data = JsonConvert.DeserializeObject<List<UserData>>(json);
}
data.ForEach(engineer =>
engineers.Add(engineer.email, engineer.id));
try to create class that represent the data in json object for example
Class obj
{
public int Id { get ; set; }
public string email { get ; set; }
public string username { get ; set; }
public string state { get ; set; }
public string email { get ; set; }
}
then
using System.Web.Script.Serialization;
var js = new JavaScriptSerializer();
List<obj> list = js.Deserialize<List<obj>>(jsonString);
after that you can access all list items id and email by using foreach
I am trying to update a List which is a List of Interfaces to concrete classes.
I add to the List each Market type i am interested in, for this Example these Markets are A and B
I loop over all the markets, (sample provided with 3 markets A B & C, we are only interested in A and B) And determine which is of interest to us.
Once found we pass this to an extraction method too do its work and create an instance of the Correct Market_ class type.
This all works fine, but when i try to update the list with the Updates it does not get reflected in the List.
Code below, any Suggestions?
Thanks
public class Test
{
public Test()
{
TheMarkets MarketsToUpdate = new TheMarkets();
List<SpecificCompanyMarket> lstMarks = new List<SpecificCompanyMarket>();
lstMarks.Add(new SpecificCompanyMarket(1234, "A", "Some HTML DATA HERE"));
lstMarks.Add(new SpecificCompanyMarket(5874, "B", "Some HTML DATA HERE"));
lstMarks.Add(new SpecificCompanyMarket(2224, "C", "Some HTML DATA HERE"));
foreach (var item in lstMarks)
{
if (MarketsToUpdate.IsMarketWeAreInterestedIn(item.MarketName))
{
ITheMarkets MarkToUpdate = ExtractMarketData(item);
var obj = MarketsToUpdate.MarketsWeAreInterestedIn.FirstOrDefault(x => x.MarketName() == "A");
if (obj != null)
{
obj = MarkToUpdate;
}
}
}
//Look At MarketsToUpdate Now and the item has not changed, still original values
//I was expecting to see the new values for the fields in A, not the default 0's
}
public ITheMarkets ExtractMarketData(SpecificCompanyMarket item)
{
ITheMarkets market = null;
if (item.MarketName.ToUpper() == "A")
{
Market_A marketType = new Market_A();
marketType.SomeValue1 = 123;
marketType.SomeValue2 = 158253;
market = marketType;
}
//Other Market extractions here
return market;
}
}
public class SpecificCompanyMarket
{
public int MarketId { get; set; }
public string MarketName { get; set; }
public string MarketDataHTML { get; set; }
public SpecificCompanyMarket(int MID, string MName, string MData)
{
MarketId = MID;
MarketName = MName;
MarketDataHTML = MData;
}
}
public class TheMarkets
{
public List<ITheMarkets> MarketsWeAreInterestedIn = new List<ITheMarkets>();
public TheMarkets()
{
Market_A A = new Market_A();
Market_B B = new Market_B();
MarketsWeAreInterestedIn.Add(A);
MarketsWeAreInterestedIn.Add(B);
}
public bool IsMarketWeAreInterestedIn(string strMarketName)
{
bool blnRetVal = false;
foreach (var item in MarketsWeAreInterestedIn)
{
if (item.MarketName().ToUpper().Trim().Equals(strMarketName.ToUpper().Trim()))
{
blnRetVal = true;
break;
}
}
return blnRetVal;
}
}
public interface ITheMarkets
{
string MarketName();
}
public class Market_A : ITheMarkets
{
public string LabelType { get; private set; }
public double SomeValue1 { get; set; }
public double SomeValue2 { get; set; }
public double SomeValue3 { get; set; }
public Market_A()
{
LabelType = "A";
}
public string MarketName()
{
return LabelType;
}
}
public class Market_B : ITheMarkets
{
public string LabelType { get; private set; }
public List<string> SomeList { get; set; }
public double SomeValue { get; set; }
public Market_B()
{
LabelType = "B";
}
public string MarketName()
{
return LabelType;
}
}
This is a short example to get you going. Loop through your list, find the object you want to update, create a new object of that type and then find the original objects index in the list and overwrite it in place. You are essentially just replacing the object in the list with a new one not mutating the existing one.
foreach (var item in lstMarks)
{
//your code to get an object with data to update
var yourObjectToUpdate = item.GetTheOneYouWant();
//make updates
yourObjectToUpdate.SomeProperty = "New Value";
int index = lstMarks.IndexOf(item);
lstMarks[index] = yourObjectToUpdate;
}
You are extracting an obj from marketWeAreInterestedIn list using LINQ's firstOrDefault extension. This is a new object and not a reference to the obj in that list. Therefore, no updates will be reflected in the object inside that list. Try using 'indexof'
You are not storing "list of interfaces" in your list. List<T> stores an array of pointers to objects that support T interface. Once you enumerate (with Linq in your case) your list, you copy a pointer from list, which is not associated with list itself in any way. It is just a pointer to your instance.
To do what you want, you will have to build new list while enumerating the original one, adding objects to it, according to your needs, so the second list will be based on the first one but with changes applied that you need.
You can also replace specific instance at specific index instead of building new list in your code, but to do this you will need to enumerate your list with for loop and know an index for each item:
list[index] = newvalue;
But there is a third solution to update list item directly by Proxying them. This is an example
class ItemProxy : T { public T Value { get; set; } }
var list = new List<ItemProxy<MyClass>>();
list.Insert(new ItemProxy { Value = new MyClass() });
list.Insert(new ItemProxy { Value = new MyClass() });
list.Insert(new ItemProxy { Value = new MyClass() });
foreach(var item in list)
if(item // ...)
item.Value = new MyClass(); // done, pointer in the list is updated.
Third is the best case for perfomance, but it will be better to use this proxying class for something more than just proxying.
I'm attempting to read a big list of data into a flat CSV. One field of each row is XML data - with the XML dictating additional Properties in each row. Therefore each row could have slightly different Properties.
I've got my list in an initial structured class:
private class Response {
public Response() {
Values = new Dictionary<string, string>();
}
public string Owner { get; set; }
public string Author { get; set; }
public string Email { get; set; }
public string Data { get; set; } // XML data in here
public Dictionary<string, string> Values { get; set; }
public DateTime Created { get; set; }
}
I then thought to make my list dynamic to handle the varied Properties:
var responses = new List<dynamic>();
foreach (var response in query) {
if (!string.IsNullOrEmpty(response.Data))
{
var doc = new XmlDocument();
doc.LoadXml(response.Data);
foreach (XmlNode node in doc.GetElementsByTagName("field")) {
try
{
response.Values.Add(node.FirstChild.InnerText, node.LastChild.InnerText);
}
catch (Exception ex) {
// log
}
}
}
dynamic fullResponse = new ExpandoObject();
fullResponse.Owner = response.Owner;
fullResponse.Author = response.Author;
fullResponse.Email = response.Email;
fullResponse.Created = response.Created;
IDictionary<string, object> map = fullResponse;
foreach (var value in response.Values) {
if (map.ContainsKey(value.Key)) {
map[value.Key] = value.Value;
}
else {
map.Add(value.Key, value.Value);
}
}
responses.Add(fullResponse);
}
... which also works fine. But now I want to basically flatten this list and export it as a CSV, knowing that each row of my dynamic list might have slightly different properties.
Grabbing the PropertyInfo, a dynamic type, obviously comes back with nothing. Am I just going to have to loop through my list to extract the unique properties manually into something like a DataTable? Or are there some calls I can make with Reflection to get this done more efficiently?
I ended up using a plain old DataTable to get it sorted:
using (var dt = new DataTable())
{
var keys = responses.SelectMany(x => ((IDictionary<string, object>)x).Keys).Distinct();
var columns = keys.Select(x => new DataColumn(x)).ToArray();
dt.Columns.AddRange(columns);
foreach(IDictionary<string, object> response in responses)
{
var row = dt.NewRow();
foreach (var kvp in response)
{
row[kvp.Key] = kvp.Value;
}
dt.Rows.Add(row);
}
// write to CSV
}
Though I feel like I could've done something a lot cooler with Reflection to achieve the same result.
What's the difference between JsonConvert.DeserializeObject and JObject.Parse? As far as I can tell, both take a string and are in the Json.NET library. What kind of situation would make one more convenient than the other, or is it mainly just preference?
For reference, here's an example of me using both to do exactly the same thing - parse a Json string and return a list of one of the Json attributes.
public ActionResult ReadJson()
{
string countiesJson = "{'Everything':[{'county_name':null,'description':null,'feat_class':'Civil','feature_id':'36865',"
+"'fips_class':'H1','fips_county_cd':'1','full_county_name':null,'link_title':null,'url':'http://www.alachuacounty.us/','name':'Alachua County'"+ ",'primary_latitude':'29.7','primary_longitude':'-82.33','state_abbreviation':'FL','state_name':'Florida'},"+
"{'county_name':null,'description':null,"+ "'feat_class':'Civil','feature_id':'36866','fips_class':'H1','fips_county_cd':'3','full_county_name':null,'link_title':null,'url':'http://www.bakercountyfl.org/','name':'Baker County','primary_latitude':'30.33','primary_longitude':'-82.29','state_abbreviation':'FL','state_name':'Florida'}]}";
//Can use either JSONParseObject or JSONParseDynamic here
List<string> counties = JSONParseObject(countiesJson);
JSONParseDynamic(countiesJson);
return View(counties);
}
public List<string> JSONParseObject(string jsonText)
{
JObject jResults = JObject.Parse(jsonText);
List<string> counties = new List<string>();
foreach (var county in jResults["Everything"])
{
counties.Add((string)county["name"]);
}
return counties;
}
public List<string> JSONParseDynamic(string jsonText)
{
dynamic jResults = JsonConvert.DeserializeObject(jsonText);
List<string> counties = new List<string>();
foreach(var county in jResults.Everything)
{
counties.Add((string)county.name);
}
return counties;
}
The LINQ-to-JSON API (JObject, JToken, etc.) exists to allow working with JSON without needing to know its structure ahead of time. You can deserialize any arbitrary JSON using JToken.Parse, then examine and manipulate its contents using other JToken methods. LINQ-to-JSON also works well if you just need one or two values from the JSON (such as the name of a county).
JsonConvert.DeserializeObject, on the other hand, is mainly intended to be used when you DO know the structure of the JSON ahead of time and you want to deserialize into strongly typed classes. For example, here's how you would get the full set of county data from your JSON into a list of County objects.
class Program
{
static void Main(string[] args)
{
string countiesJson = "{'Everything':[{'county_name':null,'description':null,'feat_class':'Civil','feature_id':'36865',"
+"'fips_class':'H1','fips_county_cd':'1','full_county_name':null,'link_title':null,'url':'http://www.alachuacounty.us/','name':'Alachua County'"+ ",'primary_latitude':'29.7','primary_longitude':'-82.33','state_abbreviation':'FL','state_name':'Florida'},"+
"{'county_name':null,'description':null,"+ "'feat_class':'Civil','feature_id':'36866','fips_class':'H1','fips_county_cd':'3','full_county_name':null,'link_title':null,'url':'http://www.bakercountyfl.org/','name':'Baker County','primary_latitude':'30.33','primary_longitude':'-82.29','state_abbreviation':'FL','state_name':'Florida'}]}";
foreach (County c in JsonParseCounties(countiesJson))
{
Console.WriteLine(string.Format("{0}, {1} ({2},{3})", c.name,
c.state_abbreviation, c.primary_latitude, c.primary_longitude));
}
}
public static List<County> JsonParseCounties(string jsonText)
{
return JsonConvert.DeserializeObject<RootObject>(jsonText).Counties;
}
}
public class RootObject
{
[JsonProperty("Everything")]
public List<County> Counties { get; set; }
}
public class County
{
public string county_name { get; set; }
public string description { get; set; }
public string feat_class { get; set; }
public string feature_id { get; set; }
public string fips_class { get; set; }
public string fips_county_cd { get; set; }
public string full_county_name { get; set; }
public string link_title { get; set; }
public string url { get; set; }
public string name { get; set; }
public string primary_latitude { get; set; }
public string primary_longitude { get; set; }
public string state_abbreviation { get; set; }
public string state_name { get; set; }
}
Notice that Json.Net uses the type argument given to the JsonConvert.DeserializeObject method to determine what type of object to create.
Of course, if you don't specify a type when you call DeserializeObject, or you use object or dynamic, then Json.Net has no choice but to deserialize into a JObject. (You can see for yourself that your dynamic variable actually holds a JObject by checking jResults.GetType().FullName.) So in that case, there's not much difference between JsonConvert.DeserializeObject and JToken.Parse; either will give you the same result.
JsonConvert.DeserializeObject has one advantage over JObject.Parse:
It is possible to use custom JsonSerializerSettings.
This can be very useful e.g. if you want to control how dates are deserialized.
By default dates are deserialized into DateTime objects.
This means that you may end up with a date with another time zone than the one in the json string.
You can change this behaviour by creating a JsonSerializerSetting and setting
DateParseHandling to DateParseHandling.DateTimeOffset.
An example:
var json = #"{ ""Time"": ""2015-10-28T14:05:22.0091621+00:00""}";
Console.WriteLine(json);
// Result: { "Time": "2015-10-28T14:05:22.0091621+00:00" }
var jObject1 = JObject.Parse(json);
Console.WriteLine(jObject1.ToString());
// Result: { "Time": "2015-10-28T15:05:22.0091621+01:00" }
var jObject2 = Newtonsoft.Json.JsonConvert.DeserializeObject(json,
new Newtonsoft.Json.JsonSerializerSettings
{
DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTimeOffset
});
Console.WriteLine(jObject2.ToString());
// Result: { "Time": "2015-10-28T14:05:22.0091621+00:00" }
For me the key difference I was interested in was Speed.
I made a simple test to find out if it was faster to use JToken.Parse(string) or DeserializeObject<JToken>(string) to create a large amount of JToken and these were the results after 2,000,000 iterations using a sample of real world data
Method
Operating System Ticks
Milliseconds
JsonConvert
86123945
8612ms
JToken
67671724
6767ms
There was some variation between runs but the difference was always large.
Here is the test so you can modify it or run it yourself:
private static string s = #"{'stream':'btcusdt #bookTicker','data':{'u':20430107433,'s':'BTCUSDT','b':'21223.72000000','B':'3.29440000','a':'21223.73000000','A':'2.05450000'}}";
private static Stopwatch sw = new Stopwatch();
private static void Main(string[] args)
{
JToken convert = default;
sw.Restart();
for (int i = 0; i < 2000000; i++)
{
convert = JsonConvert.DeserializeObject<JToken>(s);
}
Console.WriteLine("JsonConvert: " + sw.ElapsedTicks + " [" + sw.ElapsedMilliseconds + "ms]");
convert.ToString();
convert = default;
sw.Restart();
for (int i = 0; i < 2000000; i++)
{
convert = JToken.Parse(s);
}
Console.WriteLine("JToken : " + sw.ElapsedTicks + " [" + sw.ElapsedMilliseconds + "ms]");
convert.ToString();
Console.ReadLine();
}
I knew an advantage that JsonConvert.DeserializeObject can deserialize an Array/List json text directly, but JObject cannot.
Try below sample code:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace NetCoreJsonNETDemo
{
internal class Person
{
[JsonProperty]
internal string Name
{
get;
set;
}
[JsonProperty]
internal int? Age
{
get;
set;
}
}
internal class PersonContainer
{
public List<Person> Persons
{
get;
set;
}
}
class Program
{
static T RecoverPersonsWithJsonConvert<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
static T RecoverPersonsWithJObejct<T>(string json) where T : class
{
try
{
return JObject.Parse(json).ToObject<T>();
}
catch (Exception ex)
{
Console.WriteLine("JObject threw an Exception: " + ex.Message);
return null;
}
}
static void Main(string[] args)
{
List<Person> persons = new List<Person>();
persons.Add(new Person()
{
Name = "Jack",
Age = 18
});
persons.Add(new Person()
{
Name = "Sam",
Age = null
});
persons.Add(new Person()
{
Name = "Bob",
Age = 36
});
string json = JsonConvert.SerializeObject(persons, new JsonSerializerSettings()
{
Formatting = Formatting.Indented
});
List<Person> newPersons = RecoverPersonsWithJsonConvert<List<Person>>(json);
newPersons = RecoverPersonsWithJObejct<List<Person>>(json);//JObject will throw an error, since the json text is an array.
PersonContainer personContainer = new PersonContainer()
{
Persons = persons
};
json = JsonConvert.SerializeObject(personContainer, new JsonSerializerSettings()
{
Formatting = Formatting.Indented
});
newPersons = RecoverPersonsWithJObejct<PersonContainer>(json).Persons;
newPersons = null;
newPersons = RecoverPersonsWithJsonConvert<PersonContainer>(json).Persons;
Console.WriteLine("Press any key to end...");
Console.ReadKey();
}
}
}
Apart from the answers provided here around usage, which are correct as per me :
Jobject.Parse -> when the Json is not strongly Typed or you do not know the structure of Json ahead of time
JsonConvert.DeserializeObject<T> -> When you know which class or type to cast the Json in. T can be a complex class or a simple type
My answer is based on the performance in case where the structure is not known, as given in the OP code, if we benchmark the usage of both methods for performance, it is observed that Jobject.Parse() fares well in terms of allocated memory, please ignore the name of methods, I am first calling the method with 'JsonConvert.DeserializeObject' and then second method is with Jobject.Parse