I'm trying to add the contents of a JSON file to a LIST. Normally, I would use a loop to iterate through the objects, but using COUNT will not compile and when I use LENGTH, it counts the number of characters in the string.
Do I need to make it a JSONArray when the object is made, and if so, how do I do that? Or do I need another kind of loop? I'm using version 5.2.3f, the last XP compatible version.
Thanks!
You can use MiniJson:
var jsonString = File.ReadAllText(jsonFileName);
var list = Json.Deserialize(jsonString) as List<object>;
Related
I have Json Collection with the different fields. All fields are dynamic. Please take the below example.
[{"KB":"1","Id":"01","MemCode":1,"A":"2","B":"1","C":"2010-01-01T00:00:00","D":1}
{"KB":"1","Id":"01","MemCode":2,"A":"2","B":"1","C":"2010-01-01T00:00:00","D":2},
{"KB":"1","Id":"01","MemCode":2,"A":"2","B":"1","C":"2010-01-01T00:00:00","D":3},
{"KB":"1","Id":"01","MemCode":2,"A":"2","B":"1","C":"2010-01-01T00:00:00","D":4}]
I want to compare Four number json with the first one and identify the changes,
Like in fourth line Memcode is 2 and in first Memcode is 1. So here memcode is change from 2 to 1.
Like wise for all the fields. this field may be any type like datetime/ string etc. This is just example. JSON may be long with many fields. But all json string is same fields.
All fields are dynamic. I want some method which do above calculation and return field change with the old and new values.
I want to do using C# and Newtonsoft.Json. I don't know how to achieve above one. Can you please help me/guide me?
Thank you in advance.
EDIT :- 5/10
Hello, Sorry If I am not clear. Let me Explain Once again. I want develop some generic method who accept the collection of the JSON. This JSON have a number of different fields.
Suppose Collection have a 5 JSON. ALl 5 JSON have a same number of fields with a different value or may be same values.
Now I want to compare 1st number of JSON with the N number of JSON. Identify which field has been changes. Take that field and it's old value/New value in the Collection. Old value will be N field value and New value will be 1 field value. Continue this way for other JSON. Now 1st Number JSON compare with the N-1. and identify change fields. Continue this way up to all collection finished.
Return value be Fields and Old value, New value.
The field can by string, number of date.
I can do using for loop but I want some generic method which is time efficient and align with the new C# feature.
Hope I am clear this time.
Thank you so much..
Use dynamic and convert your Json object as bellow
dynamic data= JsonConvert.DeserializeObject(your Json Object);
Then use normal foreach loop on data to compare
You could convert each JSON object to List<string> where string represents one or more JSON attributes. Then compare those lists using Except method. Each JSON object is serialized to string which is then split by ,. By splitting, JSON attributes are extracted. objArray is the array containing JSON objects.
List<List<string>> jsonAttList = new List<List<string>>();
int objArrayLength = objArray.Length;
for (int i = 0; i < objArrayLength; i++)
{
string objString = JsonConvert.SerializeObject(objArray[i]);
jsonAttList.Add(objString.Split(',').ToList());
}
Or shorter
List<List<string>> jsonAttList = new List<List<string>>();
objArray.ForEach(item => jsonAttList.Add(JsonConvert.SerializeObject(item).Split(',').ToList()));
Here are four examples you provided with one additional attribute.
[{"KB":"1","Id":"01","MemCode":1,"A":"2","B":"1","myObj":{"X":1,"Y":2},"C":"2010-01-01T00:00:00","D":1},
{"KB":"1","Id":"01","MemCode":2,"A":"2","B":"1","C":"2010-01-01T00:00:00","D":2}
{"KB":"1","Id":"01","MemCode":2,"A":"2","B":"1","myObj":{"X":1,"Y":3},"C":"2010-01-01T00:00:00","D":3},
{"KB":"1","Id":"01","MemCode":2,"A":"2","B":"1","myObj":{"X":1,"Y":2,"Z":3},"C":"2010-01-01T00:00:00","D":4}]
Difference between two JSON objects is list of strings.
Difference between first and second JSON object is list containing: "MemCode":1, "myObj":{"X":1, "Y":2} and "D":1}.
var difference01 = jsonAttList[0].Except(jsonAttList[1]).ToList();
Difference between first and third JSON object is list containing: "MemCode":1, "Y":2} and "D":1}.
var difference02 = jsonAttList[0].Except(jsonAttList[2]).ToList();
Difference between first and fourth JSON object is list containing: "MemCode":1, "Y":2} and "D":1}.
var difference03 = jsonAttList[0].Except(jsonAttList[3]).ToList();
Difference between fourth and first JSON object is list containing: "MemCode":2, "Y":2, "Z":3} and "D":4}.
var difference30 = jsonAttList[3].Except(jsonAttList[0]).ToList();
In C# I'm storing values in an array.
So to create this array I'm using this code, 'int[] values = new int[10];'
But, what if I need more than 10 values, or in the case I never know how many values I will have. Could be 1, 10 or 100.
I understand the idea that I need to let the compiler know how big the array should be so it can allocate memory space for it.
Is there a way to work around that?
You could just use a List and let it do all the heavy lifting for you:
List<int> values = new List<int>();
Arrays must have defined length. If you want dynamic size, consider using List class.
Please take a look at and research the concept of "Immutable objects"
An array has a fixed size, If you need an array with a dynamic size it is best to either create extension methods or a handler that does the work for you.
The work to be done is to get the array, create a new array with the new size based on whether you want to add or remove something, and to populate the new array with the data from the previous array. This will create a new object instead of modifying the previous object and will make sure you don't push items to a full array, or have an array with a size larger than the items that fit in it.
Ofcourse the List class would work as well and would probably solve your problem.
I have a string variable like so, which I am receiving from a third party API:
string strArray = "[[1,\"56353657\",\"300\",\"test\",\"<img src=\\\"../Images/Edit.gif\\\" id=\\\"Edit\\\" />\",\"<img src=\\\"../Images/Delete.gif\\\" id=\\\"Delete\\\" />\"],[2,\"56353657\",\"400\",\"test\",\"<img src=\\\"../Images/Edit.gif\\\" id=\\\"Edit\\\" />\",\"<img src=\\\"../Images/Delete.gif\\\" id=\\\"Delete\\\" />\"]]";
I would like to be able to loop through this and retrieve the first 3 items in each of the arrays.
Could someone please advise me as to how to achieve this using c#?
Because values in your array of arrays are not of the same type you can try this way:
String[][] table = JsonConvert.DeserializeObject<String[][]>(strArray);
Then you can loop through this and, if you need, convert values to the desired type.
I'm deserialising JSON using JSON.Net along the same lines as the accepted solution to this question: Deserialize json object into dynamic object using Json.net. Essentially:
dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");
Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);
Difference being my array has strings rather than numbers. The above methods work fine. However, what I want to do is test if the array contains a particular value. If it was a typed array of strings I could use myArray.IndexOf("ValueToFind") and if it returns a value > -1 then it's in there. However, this isn't working and I think it's because it's actually an array of JValues rather than strings.
I can iterate through the array, cast each one to a string and then test (i.e. a foreach loop with an if statement inside) but I was hoping for a more succinct single line test. Can anyone advise if there is a simpler way to do the test?
Thanks
JSON.NET can seamlessly convert JArray to List<string>, so you can use
Console.WriteLine(d.array.ToObject<List<string>>().IndexOf("1"));
This works even with JSON integer array.
I got a slightly messier answer by first converting your dynamic array to a known type:
IEnumerable<JToken> d2 = d.array;
Then you can use Any as an extension method.
if (d2.Any(p => p.ToString() == "1")) //etc.
I've recently started using c# moving over from Java. I can't seem to find how to get a list item by index. In java to get the first item of the list it would be:
list1.get(0);
What is the equivalent in c#?
list1[0];
Assuming list's type has an indexer defined.
You can use the ElementAt extension method on the list.
For example:
// Get the first item from the list
using System.Linq;
var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);
// Do something with firstItem
Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array:
List[index]
See, for instance, List.Item[Int32] Property.
.NET List data structure is an Array in a "mutable shell".
So you can use indexes for accessing to it's elements like:
var firstElement = myList[0];
var secondElement = myList[1];
Starting with C# 8.0 you can use Index and Range classes for accessing elements. They provides accessing from the end of sequence or just access a specific part of sequence:
var lastElement = myList[^1]; // Using Index
var fiveElements = myList[2..7]; // Using Range, note that 7 is exclusive
You can combine indexes and ranges together:
var elementsFromThirdToEnd = myList[2..^0]; // Index and Range together
Also you can use LINQ ElementAt method but for 99% of cases this is really not necessary and just slow performance solution.
Old question, but I see that this thread was fairly recently active, so I'll go ahead and throw in my two cents:
Pretty much exactly what Mitch said. Assuming proper indexing, you can just go ahead and use square bracket notation as if you were accessing an array. In addition to using the numeric index, though, if your members have specific names, you can often do kind of a simultaneous search/access by typing something like:
var temp = list1["DesiredMember"];
The more you know, right?
you can use index to access list elements
List<string> list1 = new List<string>();
list1[0] //for getting the first element of the list