Display RootObject Class and display it in datatable - c#

I am a beginner and I need help with displaying rootobject class which contain 2 lists of objects and have them show up in the datatable.
I have been finding ways, but none of them help me.
How do I access the 2 lists in RootObject Class and have them show up in the datatable?
Below is my JSON File
{
"Non_Portable": [
{
"NameOfGamingEquipments": "Playstation 4",
"ResourceId": 1,
"RentalPrice": 200,
"DeliveryMode": "Hand Carry",
"quantityOfCables": 2,
"TypeOfCable": "Micro USB for controller and HDMI for display",
"Accessories": "2 wireless Dualshock 4 controllers"
},
{
"NameOfGamingEquipments": "Xbox One",
"ResourceId": 2,
"RentalPrice": 200,
"DeliveryMode": " Hand Carry",
"quantityOfCables": 2,
"TypeOfCable": " Micro USB cable for controller and HDMI cable for display",
"Accessories": "batteries for controller"
},
{
"NameOfGamingEquipments": "Playstation 3",
"ResourceId": 3,
"RentalPrice": 120,
"DeliveryMode": "delivery via deliveryman",
"quantityOfCables": 1,
"TypeOfCable": "HDMI cable for display",
"Accessories": "Wireless dualshock 3 controller for Playstation 3"
}
],
"Portable": [
{
"NameOfGamingEquipments": "Nintendo 3DS",
"ResourceId": 4,
"RentalPrice": 50,
"DeliveryMode": "Hand carry",
"sizeOfScreen": "Top: 4.88 Bottom: 4.18",
"quantityOfCartridges": 1,
"CartridgeName": "Super Mario",
"touchScreenFunction": true
},
{
"NameOfGamingEquipments": "Sony Playstation Vita",
"ResourceId": 5,
"RentalPrice": 70,
"DeliveryMode": "Self Pick Up",
"sizeOfScreen": "5 inches",
"quantityOfCartridges": 2,
"CartridgeName": "Powerpuff Girls and GTA ",
"touchScreenFunction": true
},
{
"NameOfGamingEquipments": "Nintendo 3DS XL",
"ResourceId": 6,
"RentalPrice": 40,
"DeliveryMode": "Self Pick Up",
"sizeOfScreen": "Top: 4.88 bottom: 4.18 ",
"quantityOfCartridges": 1,
"CartridgeName": "Ridge Racer",
"touchScreenFunction": true
}
]
}
Below is my code for deserializing json data to rootobject
Rootobject ser;
string jsonstr;
private void Booking_Load(object sender, EventArgs e)
{
jsonstr = File.ReadAllText("Data.JSON");
ser = JsonConvert.DeserializeObject<Rootobject>(jsonstr);
}
Thanks for everyone help and advice in advance!!!
UPDATE: Helped by Madhi
private void button1_Click(object sender, EventArgs e)
{
/* DataTable table = ConvertListToDataTable(ser.Non_Portable);
dataGridView1.DataSource = table;*/
DataTable dt = new DataTable();
dataGridView1.DataSource = dt;
dt.Columns.Add("NameOfGamingEquipment");
dt.Columns.Add("ResourceId");
dt.Columns.Add("RentalPrice");
// Add more columns
foreach (var item in ser.Portable)
{
var row = dt.NewRow();
row["NameOfGamingEquipment"] = item.NameOfGamingEquipments;
row["ResourceId"] = Convert.ToString(item.ResourceId);
row["RentalPrice"] = item.RentalPrice;
dt.Rows.Add(row);
}
}
I am not sure why the table is not showing up..

I assume your deserialization is successful. Then you can populate your datatable like this:
var json = File.ReadAllText(#"C:\Path\json.txt");
var test = JsonConvert.DeserializeObject<RootObject>(json);
DataTable dt = new DataTable();
dt.Columns.Add("NameOfGamingEquipment");
dt.Columns.Add("ResourceId");
dt.Columns.Add("RentalPrice");
dt.Columns.Add("DeliveryMode");
dt.Columns.Add("QuantityOfCables");
dt.Columns.Add("TypeOfCable");
dt.Columns.Add("Accessories");
foreach (var item in test.Non_Portable)
{
var row = dt.NewRow();
row["NameOfGamingEquipment"] = item.NameOfGamingEquipments;
row["ResourceId"] = Convert.ToString(item.ResourceId);
row["RentalPrice"] = item.RentalPrice;
row["DeliveryMode"] = item.DeliveryMode;
row["quantityOfCables"] = item.quantityOfCables;
row["TypeOfCable"] = item.TypeOfCable;
row["Accessories"] = item.Accessories;
dt.Rows.Add(row);
}
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
Do the same for your other list (Portable).
This is the result:
The RootObject class:
public class NonPortable
{
public string NameOfGamingEquipments { get; set; }
public int ResourceId { get; set; }
public int RentalPrice { get; set; }
public string DeliveryMode { get; set; }
public int quantityOfCables { get; set; }
public string TypeOfCable { get; set; }
public string Accessories { get; set; }
}
public class Portable
{
public string NameOfGamingEquipments { get; set; }
public int ResourceId { get; set; }
public int RentalPrice { get; set; }
public string DeliveryMode { get; set; }
public string sizeOfScreen { get; set; }
public int quantityOfCartridges { get; set; }
public string CartridgeName { get; set; }
public bool touchScreenFunction { get; set; }
}
public class RootObject
{
public List<NonPortable> Non_Portable { get; set; }
public List<Portable> Portable { get; set; }
}

Related

Keep application-specific fields synced with database

I have a GameConsole model :
public class GameConsole
{
public int ID { get; protected set; } = 0;
public string Identifier { get; protected set; } = "GameConsole";
public List<string> ValidInputs { get; set; } = new List<string>(8);
public Dictionary<string, InputAxis> InputAxesMap { get; protected set; } = new Dictionary<string, InputAxis>(8);
public Dictionary<string, InputButton> InputButtonMap { get; protected set; } = new Dictionary<string, InputButton>(32);
public string ValidInputsStr { get; set; } = string.Empty;
public string InputAxesMapStr { get; set; } = string.Empty;
public string InputButtonMapStr { get; set; } = string.Empty;
}
I need ValidInputs, InputAxesMap, and InputButtonMap stored in an SQLite database. I've done this by serializing to JSON in their respective ValidInputsStr, InputAxesMapStr, and InputButtonMapStr fields.
However, I need to use these lists and dictionaries in the application. But each time I open the database context, ValidInputs, InputAxesMap, and InputButtonMap don't contain the data (unless I deserialize them from the JSON strings).
using (MyDatabaseContext context = new MyDatabaseContext(databasePath))
{
GameConsole gmConsole = context.Consoles.First((console) => console.Identifier == "GC");
Console.WriteLine(gmConsole.InputButtonMap.Count); //Prints 0
gmConsole.ReadInJSONFields(); //This is what I want to eliminate
Console.WriteLine(gmConsole.InputButtonMap.Count); //Has the proper data after reading from JSON
}
This is inconvenient considering there will be more objects in the future. How can I have everything be read and written directly to and from the database, and have these fields be populated?
An example GameConsole in JSON form:
{
"Identifier": "GC",
"ValidInputs": [
"left",
"up",
"a",
"b"
],
"InputAxesMap": {
"left": {
"AxisVal": 0,
"MinAxisVal": 0.0,
"MaxAxisVal": -1.0,
"MaxPercentPressed": 100
},
"up": {
"AxisVal": 1,
"MinAxisVal": 0.0,
"MaxAxisVal": -1.0,
"MaxPercentPressed": 100
},
"InputButtonMap": {
"a": {
"ButtonVal": 0
},
"b": {
"ButtonVal": 1
}
}
}

loop through the json url

I got a json Url but I've got more Forenames in it. Right now it only shows one Forename.
public class details
{
public string id { get; set; }
public string name { get; set; }
public int lID { get; set; }
public string uuid { get; set; }
public string wpUID { get; set; }
public string fname { get; set; }
}
private void Form2_Load(object sender, EventArgs e){
var json1 = new WebClient().DownloadString("http://dev.ibeaconlivinglab.com:1881/showemployeesbyhu
urders?id=" + companyID);
List<details> detailsList = JsonConvert.DeserializeObject<List<details>>(json1);
foreach (details dets1 in detailsList)
{
label3.Text = dets1.fname;
this.Controls.Add(label3);
}
}
Json :
[
{
"id": 1,
"fname": "Jeff",
},
{
"id": 1,
"fname": "Jan",
},
{
"id": 1,
"fname": "Piet",
}
]
Problem is code is updating the same label again and again.
Try creating new Label each detail.
FlowLayoutPanel flowLayoutPanel1 = new FlowLayoutPanel();
flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
flowLayoutPanel1.WrapContents = false;
flowLayoutPanel1.AutoScroll = true;
this.Controls.Add(flowLayoutPanel1);
foreach (details dets1 in detailsList)
{
var label = new Label();
label.Name = dets1.fname;
label.Text = dets1.fname;
flowLayoutPanel1.Controls.Add(label);
}

Parsing JSON with JObject

I need to parse a JSON, I am already parsing the first part of the record but I am having a problem with a sub record. This is my code:
List<JToken> results = new List<JToken>();
List<JToken> results2 = new List<JToken>();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
results = JObject.Parse(result).SelectToken("record").ToList();
}
List<Record> users = new List<Record>();
foreach (JObject token in results)
{
Record user = new Record();
user.id = Int32.Parse(token["id"].ToString());
user.full_name = token["full_name"].ToString();
user.email = token["email"].ToString();
//role.RoleName = token.SelectToken("name").ToString();
}
That's working perfectly but I have issues parsin a string that's a bit deeper. This is the JSON:
{
"record": [
{
"id": 2,
"institution_id": 1,
"full_name": "",
"email": "",
"role_id": 2,
"created": "2015-01-13 01:18:52.370379",
"updated": "2015-01-22 23:58:44.103636",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "Test Branch"
}
}
]
}
I want to get the "branch_name" inside Branch_by_branch_id. How can I access it with Jobject?
If your JSON is this
{
"record": [
{
"id": 26,
"full_name": "",
"email": "",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "NAME"
}
}
]
}
Have classes like this:
public class BranchByBranchId
{
public int id { get; set; }
public int institution_id { get; set; }
public string branch_name { get; set; }
}
public class Record
{
public int id { get; set; }
public string full_name { get; set; }
public string email { get; set; }
public int branch_id { get; set; }
public BranchByBranchId Branch_by_branch_id { get; set; }
}
public class RootObject
{
public List<Record> record { get; set; }
}
Then parse it and retrieve the value like this.
var root = JsonConvert.DeserializeObject<RootObject>(json);
var branchName = root[0].Branch_by_branch_id.branch_name;
I always prefer to access my JSON objects like this, because I like having my objects as native C# classes. The classes were generated by json2csharp.

Flatten or Map objects in C#

I am trying to create generic class that will map or flatten an object.
Lets say i have this 2 classes
public class Description
{
public string Info { get; set; }
}
public class Item
{
public string Title { get; set; }
public int WordsCount { get; set; }
public string Url { get; set; }
public List<string> Headers { get; set; }
public User Owner { get; set; }
public List<Description> Descriptions { get; set; }
}
I try to create something like this:
Item item = new Item()
{
Url = "http",
Title = "home page",
Details = new Description() { Info = "some info" },
WordsCount = 220,
Headers = new List<string>() { "One", "Two", "Three" },
Descriptions = new List<Descriptions>()
{
new Description() { Info = "info 1" },
new Description() { Info = "info 2" },
new Description() { Info = "info 3" },
}
};
After the flattening/mapping i want to have something like:
Item {
Url: 'http',
Title: 'home page',
Details.Info: 'some info',
WordsCount: '220',
Headers: 'One^Two^Three',
Descriptions.0.Info: 'info 1'.
Descriptions.1.Info: 'info 2',
Descriptions.2.Info: 'info 3',
}
I tried with AutoMapper but i guess i am not able to achieve this
Any suggestions?

InvalidCastException upon displaying JSON data into a tree structure using TreeListView

My JSON looks like this:
[
{
"id": 001,
"name": "Item 1",
"tree": [
"010",
"020",
"030"
]
},
{
"id": 002,
"name": "Item 2",
"tree": [
"010",
"020",
"030"
]
},
{
"id": 003,
"name": "Item 3",
"tree": [
"010",
"020",
"030"
]
}
]
This can be modelled into C# as following:
public class Product
{
public int id { get; set; }
public string name { get; set; }
public List<string> tree { get; set; }
}
I'm trying to display this JSON data into a TreeListView in the ObjectListView libary. Ideally, it would look like this.
My current code is as following, with "data" being the TreeListView.
List<Product> Products = JsonConvert.DeserializeObject<List<Product>>(json);
data.CanExpandGetter = model => ((Product)model).tree.Count > 0;
data.ChildrenGetter = delegate(object model)
{
return ((Product)model).
tree;
};
data.SetObjects(Products);
However, this throws an System.InvalidCastException at model => ((Product)model).tree.Count > 0.
I found the solution. I changed the JSON layout a bit.
public class ProductJSON
{
public string id { get; set; }
public string name { get; set; }
public List<Tree> tree { get; set; }
}
public class Tree
{
public string id { get; set; }
public string name { get; set; }
}
public class Product
{
public string id { get; set; }
public string name { get; set; }
public List<Product> tree { get; set; }
public Product(string _id, string _name)
{
id = _id;
name = _name;
tree = new List<Product>();
}
}
...
List<ProductJSON> Products = JsonConvert.DeserializeObject<List<ProductJSON>>(json);
List<Product> ProductList = new List<Product>();
for(int i = 0; i < Products.Count; i++)
{
ProductList.Add(new Product(Products[i].id, Products[i].name));
foreach (Tree t in Products[i].tree)
{
ProductList[i].tree.Add(new Product(t.id, t.name));
}
}
data.CanExpandGetter = delegate(object x) { return true; };
data.ChildrenGetter = delegate(object x) { return ((Product)x).tree; };
cID.AspectGetter = delegate(object x) { return String.Format("{0,3:D3}", ((Product)x).id); };
cName.AspectGetter = delegate(object x) { return ((Product)x).name; };
data.Roots = ProductList;

Categories

Resources