Populating DataGridView from JSON Array [duplicate] - c#

This question already has answers here:
How to display JSON data in a DataGridView in WinForms?
(3 answers)
Closed 5 years ago.
I have a JSON with an array of products, which I want to load into my C# program as a list, and eventually, display it in a DataGridView.
JSON:
{
"products":[
{
"name":"game",
"url":"website 1",
"cash_price":"£20.00",
"category":"Playstation 4 Game"
},
{
"name":"tv",
"url":"website 2",
"cash_price":"£200.00",
"category":"electronics"
}
]
}
Product class
class Product
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("url")]
public string url { get; set; }
[JsonProperty("cash_price")]
public string cash_price { get; set; }
[JsonProperty("category")]
public string category { get; set; }
[JsonProperty("url")]
public string url { get; set; }
public static IList<Product> products = new List<Product>();
}
I run this code:
string input = File.ReadAllText(openFileDialog1.FileName);
var results = JsonConvert.DeserializeObject(input);
dataGridView1.DataSource = Product.products;
But in the DataGridView, all I'm shown is a blank grid with the headers name, url, cash_price and category. No actual entries inside the grid.
What am I doing wrong?
Thank you

Provide the Product type when deserializing like JsonConvert.DeserializeObject<Product>.
class ProductList
{
public List<Product> products { get; set; }
}
var result = JsonConvert.DeserializeObject<ProductList>(input);
dataGridView1.DataSource = result.products;
You can probably skip the JsonPropertyAttributes when the property name matches the JSON names exactly - as is the case in your example.

Related

Filter JSON Objects based on field using LINQ [duplicate]

This question already has answers here:
How to filter JSON array in C#
(3 answers)
Closed 3 years ago.
I have set of JSON Objects which contains contact details, and I have to filter them based on the field when it is true.
This is the Sample Data
{
"9002":{
"Contacts": [
{
"Source": 0,
"Id": 0,
"Details": {
"Harlson": "9015",
"adssd": "9022",
"First Name": "Gary",
"Last Name": "Harlson"
},
"Pinned": true
}
]
}
}
I want to filter all the Details based on When Pinned becomes true using LINQ query.
You could Deserialize the Json (using NewtonSoft Json) and use Linq to query the Items with Pinned=True
var rootInstance = JsonConvert.DeserializeObject<RootObject>(json);
var result = rootInstance.Id.Contacts.Where(x=>x.Pinned);
Where Classes are defined as
public class Details
{
[JsonProperty("Harlson")]
public string Harlson { get; set; }
[JsonProperty("adssd")]
public string adssd { get; set; }
[JsonProperty("First Name")]
public string FirstName { get; set; }
[JsonProperty("Last Name")]
public string LastName { get; set; }
}
public class Contact
{
public int Source { get; set; }
public int Id { get; set; }
public Details Details { get; set; }
public bool Pinned { get; set; }
}
public class Id
{
public List<Contact> Contacts { get; set; }
}
public class RootObject
{
[JsonProperty("9002")]
public Id Id { get; set; }
}
You could solve it by using JSON with LINQ:
var myObjects = JArray.Parse(json)
.OfType<JObject>()
.Where(j => j.Properties().First().Value["Contacts"].Any(t => (bool)t["Pinned"] == true))
.ToList();
It all depends what you should do with the data. I would personally go with Anu Viswan's answer, but if you just need a small portion of the data this might be a viable solution.
https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm

Add Items to Custom Class List [duplicate]

This question already has answers here:
Add multiple items to a list
(5 answers)
Closed 3 years ago.
I was wondering if someone could help me. I have 2 classes:
`public class EventPutDto
{
//public string id { get; set; }
public string eventGbsCode { get; set; }
//public string portfolioId { get; set; }
public string businessUnitId { get; set; }
public List<Multilingual> multilingual { get; set; }
public bool supportedInPlatform { get; set; }
public bool gbsEnabled { get; set; }
public bool isParticipationEvent { get; set; }
}`
public class Multilingual
{
public string locale { get; set; }
public string name { get; set; }
}
I want to add a name and locale to the list property in the eventPutDto class. How do I do it? For example I want to add 3 locales so it should be something like
"en-gb" - "english name",
"it-it" - "italian name",
"es-es" - "spanish name"
I need to know this as I'm trying to post some Json to an endpoint.
Looks like what you want is a dictionary.
So, locale should not be of type string, but a Dictionary<string, string>
Read up on them, they are a collection of keys and values.

How to use Distinct on a list of object or on one or more properties of the object [duplicate]

This question already has answers here:
Linq distinct method only for a specific property [duplicate]
(2 answers)
Distinct by property of class with LINQ [duplicate]
(9 answers)
Distinct() with lambda?
(20 answers)
Closed 5 years ago.
I need to get a list of unique shipping addresses.
var shippingAddresses = ShopApi.Checkout.GetShippingAddresses(Shop.CommerceContext.AccountId).ToList();
This will give me a list of shipping addresses objects, but two of them have the same value for the Id column. How do I filter that or gets only one value to the list?
My ShippingAddress object looks like this.
public string Id { get; set; }
public string CustomerId { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string CountryId { get; set; }
I have a solution for your situation. You can filter your list again to only get 1 row for each Id value
public class ShippingAddresses
{
public string Id { get; set; }
public string CustomerId { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string CountryId { get; set; }
}
List<ShippingAddresses> shippingAddresses = new List<ShippingAddresses>();
//This statement will help you only get 1 row for each ID value
shippingAddresses = shippingAddresses.GroupBy(p => p.Id).Select(p => p.First()).ToList();
Somewhere in that ShippingAddress object, there is an underlying database query. That query needs to be modified to only include the unique results ... like this:
(from dbo in database.ShippingAddress
select dbo.Id).Distinct()

C# / Classes and custom types [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm starting my adventure with C# and don't know all the technics, but I already know what am I trying to achive:
public class Product
{
public string Name { get; set; }
public double Price { get; set; }
//public ??? Category { get; set; }
}
'Category' type should be a custom type (?) which has 8 possible string values for names (Food, clothes etc) and icons specifically for those names (Food - apple.jpg, Clothes - tshirt.jpg and so on)
How do I do that?
Often, when working with fixed size categories (8 in your case) we use enum type:
public enum ProductCategory {
Food,
Clothes,
//TODO: put all the other categories here
}
To add up icons, strings etc. we can implement extension methods:
public static class ProductCategoryExtensions {
// please, notice "this" for the extension method
public static string IconName(this ProductCategory value) {
switch (value) {
case ProductCategory.Food:
return "apple.jpg";
case ProductCategory.Clothes:
return "tshirt.jpg";
//TODO: add all the other categories here
default:
return "Unknown.jpg";
}
}
}
Finally
public class Product {
public string Name { get; set; }
public double Price { get; set; } // decimal is a better choice
public ProductCategory Category { get; set; }
}
Usage
Product test = new Product();
test.Category = ProductCategory.Clothes;
Console.Write(test.Category.IconName());
You can define the Category class like the following with predefined values:
public class Category
{
public static Category Food = new Category("Food", "apple.jpg");
// rest of the predefined values
private Category(string name, string imageName)
{
this.ImageName = imageName;
this.Name = name;
}
public string Name { get; private set; }
public string ImageName { get; private set; }
}
public class Product
{
public string Name { get; set; }
public double Price { get; set; }
public Category Category { get; set; }
}
Then, in your code you can set a product like this:
var product = new Product {Name= "product1", Price=1.2, Category = Category.Food};
So first of all you create a new Class, your custom type
public class Category {
// I recommend to use enums instead of strings to archive this
public string Name { get; set; }
// Path to the icon of the category
public string Icon { get; set; }
}
Now in your product, you can change the line commented out to:
// First Category is the type, the second one the Name
public Category Category { get; set; }
Now you can create a new Product with a category:
var category = new Product() {
Name = "ASP.NET Application",
Price = 500,
Category = new Category() {
Name = "Software",
Icon = "Software.jpg"
}
}
Now when you want to create another Product with another category, just repeat the proccess. You can also create an array of Categories and then use the array elements e.g. Category = Categories[3]. So you create one Category for food, one for Clothes etc, store them all in the array and use them for your products.

How to Convert Json Object to Array in C#

I am trying to convert a JSON object in to C# array.
this is the JSon I Getfrom the Server webrequest response:
string result = sr.ReadToEnd(); // this line get me response
result = {
"subjects": [{
"subject_id": 1,
"subject_name": "test 1",
"subject_class": 4,
"subject_year": "2015",
"subject_code": "t-1"
},{
"subject_id": 2,
"subject_name": "test 2",
"subject_class": 5,
"subject_year": "",
"subject_code": "t-2"
}]
};
dynamic item = JsonConvert.DeserializeObject<object>(result);
string iii = Convert.ToString(item["subjects"]);
I want to Get the Subjects and Save them in Array so i can use them for other purpose.
I use these to Method but always got the empty values.
List<subjects> subject1 = (List<subjects>)JsonConvert.DeserializeObject(iii, typeof(List<subjects>));
and
subjects[] subject2 = JsonConvert.DeserializeObject<subjects[]>(iii);
Please Help Me to Solve this.
And my Subject Class is..
class subjects
{
public int id { get; set; }
public string name { get; set; }
public int class_name { get; set; }
public string year { get; set; }
public string code { get; set; }
}
The property names won't match as is, because you subjects class don't have the 'subject_' prefix the JSON object has. Easiest fix is to change your property names as shown in Ali's answer. Just in case you need to keep your property names as is, you can also use a JsonProperty attribute to alter the serialization names (perhaps there's a more generic way using some sort of converter, but didn't think the amount of properties needed it)
class subjects
{
[JsonProperty("subject_id")]
public int id { get; set; }
[JsonProperty("subject_name")]
public string name { get; set; }
[JsonProperty("subject_class")]
public int class_name { get; set; }
[JsonProperty("subject_year")]
public string year { get; set; }
[JsonProperty("subject_code")]
public string code { get; set; }
}
If you never need the root subjects you can also skip it without dynamic or an extra class with something like:
subjects[] arr = JObject.Parse(result)["subjects"].ToObject<subjects[]>();
(JObject is part of the namespace Newtonsoft.Json.Linq )
You need to create a structure like this:
public class Subjects
{
public List<Subject> subjects {get;set;}
}
public class Subject
{
public string subject_id {get;set;}
public string subject_name {get;set;}
}
Then you should be able to do:
Subjects subjects = JsonConvert.DeserializeObject<Subject>(result);

Categories