I have a JSON result with the following structure:
{
"property1":1,
"property2":[[1,"A"],[2,"B"],[3,"C"],...] // Possible to get >10000 values
}
Using the above JSON data format, I am only interested to get the array values from the property2 which contains an array of array values and convert it to data table.
The above JSON result is coming from an external WEB API and here is what I have currently:
var jsonResponse = API.RetrieveData();
JObject json = JObject.Parse(jsonResponse);
JToken[] A = json["property2"].ToArray();
Logically, I can loop on the elements of Array [] A column by column and add it to the predesigned data table. My problem is that, upon using this, the performance will be affected as in most cases, the data that will be retrieved from the API is > 10000 values.
Is there any specific way to convert this kind of JSON Format to DataTable in c# with the most efficient way?
Thank you in advance.
I have Better and Fast approach for You
Step 1
Create a class that is similar to json structure
public class JsonClass
{
public string property1 { get ; set; }
public List<Dictionary<int,string>> property2 { get ; set; }
}
Step 2
Use Newtonsoft and deserialize json input to json match class
JsonClass jsonClass = JsonConvert.DeserializeObject<JsonClass>(jsonInputString);
Step 3
if you are using WPF just use
datatable.ItemSource = jsonClass ;
if you are using Winform then use BindingSource Component
BindingSource binding = new BindingSource();
binding.DataSource = jsonClass;
datatable.DataSource = binding;
Result might be
property1 | property2
---------------------------------------
"A" | Collection
Good luck
Related
My goal is to get the data from the database, serializing them into JSON format and send it to the API. The problem is that I don't know how to get right JSON format for the API.
C# Worker service collecting data from database.
from database i got:
1|John|Wick|Action|101
my API needs this JSON:
{
"Name":"John",
"Surname":"Wick",
"Type":"Action",
"Length":"101"
}
when i use in C# serializing to JSON:
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(values);
i got:
[John,Wick,Action,101]
is there any way how to add name of values to JSON ?
First split the database result based on the delimiter
string dbResult = ...; //1|John|Wick|Action|101
string[] dbResults = dbResult.Split("|");
Second create an anonymous object (if you don't want to introduce a data model class/struct/record)
var result = new
{
Name = dbResults[0],
Surname = dbResults[1],
Type = dbResults[2],
Length = dbResults[3],
};
Third serialize the anonymous object
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(result);
I have a Dictionary that has key: a string, value: a List of Entity, where Entity is a class:
public class Entity
{
public string myString { get; set; }
public int myInt { get; set; }
}
Dictionary<string, List<Entity>> myDictionary = new Dictionary<string, List<Entity>>();
List<Entity> aList = new List<Entity>();
Entity entity1 = new Entity( myString = "hi", myInt = 111);
Entity entity2 = new Entity( myString = "hello", myInt = 222);
aList.Add(entity1);
aList.Add(entity2);
myDictionary.Add("keyOne", aList);
I am trying to use ServiceStack.Text's CsvSerializer.SerializeToCsv() to serialise the dictionary and save it to a csv file.
string csv = CsvSerializer.SerializeToCsv(myDictionary);
File.WriteAllText(#"testsave.csv", csv);
But when run it and check the testsave.csv file, each entry in the dictionary is saved as a single element in a cell, and the element is saved horizontally:
Example: there are 3 entries in the dictionary and it will be stored to csv like this
So my question is, am I doing it right? and if I am, how do I deserealize the csv file and store it back into myDictionary later on.
CSV is not a very good match for hierarchical data storage. It is working as expected.
You may consider switching to json or xml serialization both of which do support hierarchical data and have feature complete serialization libraries available.
JSON.Net
System.Text.Json
System.Xml.*
Yes, this is correct. You can deserealize it using the FromCsv method:
var dictionary = File.ReadAllText("path/to/testsave.csv")
.FromCsv<Dictionary<string, List<Entity>>>();
You can read about this method here.
It is remarkable to note here that the derived file, when you use CsvSerializer.SerializeToCsv is not a CSV file with the strict definition of a CSV file, but the file that ServiceStack's class CsvSerializer generates.
I am new to c# don't know how to get a JSON array of array stored in a 2d array. I am having a JSON file with students marks like
[
[10,5,4],
[9,6,3]
]
and out of this I am using this code but getting error out at JArray
JArray a = JArray.Parse(json);
I have tried some other approaches as well but nothing helped basically what I want to do is want to create a boolean 2D array which will be populated on the basis of the above JSON record and for that purpose I want to populate the array with JSON content.
With the following valid JSON
{ "data" : [
[10,5,4],
[9,6,3]
]
}
The following class was used to hold the parsed data
public class RootObject {
public IList<IList<int>> data { get; set; }
}
which can be parsed using Json.Net
var root = JsonConvert.DeserializeObject<RoootObject>(json);
and the content accessed
var x1 = root.data[0][1]; // 5
var x2 = root.data[1][1]; // 6
I am trying to deserialize the JSON string below:
[{"Code1":"AA","Code2":"AB"},{"Code1":"BB","Code2":"BC"},
{"Code1":"A1","Code2":"A12"},{"Code1":"A2","Code2":"A23"},
{"Code1":"A4","Code2":"A45"},{"Code1":"A3","COde2":"A45"}]
into the following format:
{"Header":["Code1","Code2"], "Values":[["AA","AB"],["BB","BC"],["A1","A12"],["A2","A23"],["A4","A45"],["A3","A45"]]}
I am trying to deserialize using JsonConvert.DeseriaizeObject(). I am not able to achieve the desired format.
Ah, so you have a collection of identically structured objects, and want to convert it to something akin to a CSV table (sequence of headers, then sequence of records)?
You can convert from the objects collection format to records table format using the following method:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//other code, class declaration etc. goes here
string ObjectsToTable(string collectionJson)
{
// reading the collection from passed JSON string
JArray collection = JArray.Parse(collectionJson);
// retrieving header as a list of properties from the first element
// it is assumed all other elements have the exact same properties
List<string> header = (collection.First as JObject).Properties().Select(p => p.Name).ToList();
// retrieving values as lists of strings
// each string is corresponding to the property named in the header
List<List<string>> values = collection.Children<JObject>().Select( o => header.Select(p => o[p].ToString()).ToList() ).ToList();
// passing the table structure with the header and values
return JsonConvert.SerializeObject(new { Header = header, Values = values });
}
I am using EntityFramework, C# and MVC to build a web app. I need to create a dynamic table in RAM like this
COL1 | COL2 | COL3... etc.
1 | Val | Val
2 | Val | Val
I then need to be able to read/write it to JSON in the following format:
[
{id:1, COL1: "Val", COL2: "Val", COL3: "Val" },
{id:2, COL1: "Val", COL2: "Val", COL3: "Val" }
];
I need to be able to read and write the table to this format, dynamically add columns and rows easily.
I have tried using DataTable but that causes this error when it serializes:
Error: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.
Any recommendations would be appreciated.
EDIT: This is the code I used to build the table that causes the error, even when using JSON.NET serialization:
DataTable datatable = new DataTable();
datatable.Columns.Add("DBID");
datatable.Columns.Add("ROW");
datatable.Columns.Add("ID");
DataRow row = datatable.NewRow();
row["DBID"] = "Test";
row["ROW"] = "Test";
row["ID"] = "Test";
datatable.Rows.Add(row);
string json = JsonConvert.SerializeObject(datatable, Formatting.Indented); // <- Error here
return Content(json, "application/json");
EDIT 2 - SOLUTION:
string json = JsonConvert.SerializeObject(datatable, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
}
);
Thanks alan and T.S. for pointing me in the right direction and everyone else who answered!
As mentioned in many other posts, you can always add a reference to JSON.NET which exposes the method below:
var json = JsonConvert.SerializeObject(dataTableToConvertToJSON,
Formatting.Indented);
Update:
Try this code instead. It should take care of the error you're getting:
var dataTableToConvertToJSON = JsonConvert.SerializeObject(dataTableToConvertToJSON,
Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
To return the Json as a string use this:
return json;
To return a Json object use this:
return Json(dataTableToConvertToJSON, JsonRequestBehavior.AllowGet);
Like a variant your table can be stored like this:
public class TestClass
{
public int Id { get; set; }
public Dictionary<string,string> CR { get; set; } //Columns And Rows
}
And then create a list of this class, which represent your table : List<TestClass> and then serialize or deserialize it with custom converter.
P.S: alan idea is better)
Since you are importing/exporting this data to/from JSON, how about doing this on client side using JavaScript, though I am not sure whether that is at all an option for you or not. However, doing this gymnastic with JavaScript supports your requirement of adding col/properties dynamically, if that is what you need absolutely.
Otherwise having a simple C# class and constructing a list with that class' objects and then serializing the list should also do the job.