loop through the json url - c#

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);
}

Related

Display RootObject Class and display it in datatable

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; }
}

Adding Fulfillment to Shopify orders

This is my code in adding Fulfillment to Shopify orders but the converted json is not as expected.
Fullfillment product = new Fullfillment();
product.status = "success";
product.tracking_number = orderSent.TrackingNo;
List<LineItems> items = new List<LineItems>();
foreach (var item in orderSent.OrderLines)
{
LineItems line = new LineItems();
line.id = item.ProductName;
items.Add(line);
}
var json = JsonConvert.SerializeObject(product);
json = "{ \"fulfillment\": " + json + "}";
var json1 = JsonConvert.SerializeObject(items);
json = json + "{ \"line_items\": " + json1 + "}";
And this the converted json from this code:
{ "fulfillment": {
"id":0,
"status":"success",
"tracking_number":"xxxx12222",
}}{
"line_items": [
{
"id":"1234566645"
}
]
}
How can I turned like this:
{
"fulfillment": {
"tracking_number": null,
"line_items": [
{
"id": 466157049,
"quantity": 1
}
]
}
}
Model:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Fullfillment
{
[JsonProperty(PropertyName = "id")]
public long id { get; set; }
[JsonProperty(PropertyName = "status")]
public string status { get; set; }
[JsonProperty(PropertyName = "tracking_number")]
public string tracking_number { get; set; }
}
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LineItems
{
[JsonProperty(PropertyName = "id")]
public string id { get; set; }
}
These are the models for Fulfillment and Line Items.
Thank you in advance for giving advices and help.
This works for me:
var json = JsonConvert.SerializeObject(new
{
fullfillment = new
{
product.tracking_number,
line_items = items.Select(x => new
{
x.id,
quantity = 1
})
}
});
That gives me:
{
"fullfillment" : {
"tracking_number" : "xxxx12222",
"line_items" : [{
"id" : "1234566645",
"quantity" : 1
}
]
}
}
I started with this code to build up the JSON above:
Fullfillment product = new Fullfillment();
product.status = "success";
product.tracking_number = "xxxx12222";
List<LineItems> items = new List<LineItems>();
LineItems line = new LineItems();
line.id = "1234566645";
items.Add(line);
Obviously you need to fill in your specific data.
Change your classes like below.
public class Rootobject
{
public Fulfillment fulfillment { get; set; }
}
public class Fulfillment
{
public string tracking_number { get; set; }
public Line_Items[] line_items { get; set; }
}
public class Line_Items
{
public string id { get; set; }
public int quantity { get; set; }
}
public class JsonTest
{
public void Test()
{
var root = new Rootobject();
root.fulfillment = new Fulfillment();
root.fulfillment.tracking_number = "xxxx12222";
root.fulfillment.line_items = new List<Line_Items>() { new Line_Items() { id = "1234566645", quantity = 1 } }.ToArray();
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
}
This will give you this json.
{
"fulfillment": {
"tracking_number": "xxxx12222",
"line_items": [
{
"id": "1234566645",
"quantity": 1
}
]
}
}
Try the following
public class Rootobject
{
public Fulfillment fulfillment { get; set; }
}
public class Fulfillment
{
public string tracking_number { get; set; }
public Line_Items[] line_items { get; set; }
}
public class Line_Items
{
public string id { get; set; }
public int quantity { get; set; }
}
public class JsonTest
{
public void Test()
{
var root = new Rootobject();
root.fulfillment = new Fulfillment();
root.fulfillment.tracking_number = "xxxx12222";
root.fulfillment.line_items = new List<Line_Items>() { new Line_Items() { id = "1234566645", quantity = 1 } }.ToArray();
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
}

How to Convert List<T> to BsonArray to save a MongoDB Document

I'm having an Model Class, I need to Save it in a MongoDB Collection.
My Model Class:
public Class Employee
{
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
}
public Class Mobile
{
public string MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}
The Values are
Employee EmpInfo = new Employee()
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>()
{
{ MobNumber = "55566610", IsPreferred = true },
{ MobNumber = "55566611", IsPreferred = false },
}
}
BsonDocument _employee = new BsonDocument()
{
{ "Emp_ID", EmpInfo.EmpID },
{ "Emp_Name", EmpInfo.EmpName },
{ "Emp_Mobile", new BsonArray (EmpInfo.EmpMobile.Select(m => new
{
MobID = new ObjectId(),
MobNumber = m.MobNumber,
IsPreferred = m.IsPreferred
})) }
};
var collection = _database.GetCollection<BsonDocument>("EmployeeInfo");
collection.InsertOne(_employee);
I wish to save the above EmpInfo of type Employee in a MongoDB. But I can't able to create a BsonDocument. Kindly assist me is there is anything wrong in the above code. If yes kindly assist me.
there is no need to serialize to bson document
You can use TYPED collection and just insert data
Please see attached code snipet with updated class structure
void Main()
{
// To directly connect to a single MongoDB server
// or use a connection string
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collectionEmpInfo = database.GetCollection<Employee>("Employee");
Employee EmpInfo = new Employee
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>
{
new Mobile{ MobNumber = "55566610", IsPreferred = true, MobID = ObjectId.GenerateNewId() },
new Mobile{ MobNumber = "55566611", IsPreferred = false, MobID = ObjectId.GenerateNewId() },
}
};
collectionEmpInfo.InsertOne(EmpInfo);
var empList = collectionEmpInfo.Find(new BsonDocument()).ToList();
empList.Dump(); //dump is used in linqPad
}
public class Employee
{
public ObjectId Id { get; set; }
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
}
public class Mobile
{
public ObjectId MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}
In addition to answer above, I can suggest following code if you want to deal directly with Bson for some reason:
BsonDocument _employee = new BsonDocument()
{
{ "Emp_ID", EmpInfo.EmpID },
{ "Emp_Name", EmpInfo.EmpName },
{ "Emp_Mobile", BsonArray.Create(EmpInfo.EmpMobile.Select(m => new BsonDocument()
{
{ "MobID" , new ObjectId() },
{ "MobNumber", m.MobNumber },
{ "IsPreferred", m.IsPreferred }
})) }
};
The reason of the error you've got is that BsonArray.Create creates an array of values, not an array of objects. See this question for details.

How to Get Values from a json response string in C#

I want to get "id" "gender", "name", "picture" from a this json response string
{
"data": [{
"name": "XXX",
"gender": "male",
"id": "528814",
"picture": {
"data": {
"is_silhouette": false,
"url": "https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-frc3\/v\/t1.0-1\/p50x50\/551182_10152227358459008__n.jpg?oh=983b70686285c2f60f71e665ace8ed5f&oe=54C1220C&__gda__=1422017140_998fbe013c4fe191ccadfdbc77693a76"
}
}
}
string[] data = friendsData.Split(new string[] { "}," }, StringSplitOptions.RemoveEmptyEntries).ToArray();
foreach (string d in data)
{
try
{
FacebookFriend f = new FacebookFriend
{
id = d.Substring("\"id\":\"", "\""),
gender = d.Substring("gender\":\"", "\""),
name = d.Substring("name\":\"", "\""),
picture = d.Substring("\"picture\":{\"data\":{\"url\":\"", "\"").Replace(#"\", string.Empty)
};
FacebookFriendList.Add(f);
}
catch
{
continue;
}
}
This code looks bad if the json data changes then you need to modify your logic accordingly. I would suggest you to serialize and deserialize the model data using Json serialization.
Model:
public class SerializationModel
{
public Data Data { get; set; }
}
public class Data
{
public string Name { get; set; }
public string Gender { get; set; }
public string Id { get; set; }
public Picture Picture { get; set; }
}
public class Picture
{
public PictureData Data { get; set; }
}
public class PictureData
{
public bool is_silhouette { get; set; }
public string url { get; set; }
}
Serialize your data to get the json output is like,
SerializationModel serializationModel = new SerializationModel
{
Data = new Data
{
Gender = "mALE",
Id = "88",
Name = "User",
Picture = new Picture
{
Data = new PictureData
{
is_silhouette = true,
url = "www.google.com"
}
}
}
};
string serializedString = Newtonsoft.Json.JsonConvert.SerializeObject(serializationModel);
which would yield the below result,
{"Data":{"Name":"User","Gender":"mALE","Id":"88","Picture":{"Data":{"is_silhouette":true,"url":"www.google.com"}}}}
To deserialize the json data back to the model,
SerializationModel sm = Newtonsoft.Json.JsonConvert.DeserializeObject<SerializationModel>(serializedString);
Then you can get the required values from the model itself.

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