Select an item, with an specific json property value, using as a dataset a list of objects with one property beeing a json - json.net

I have the following list.
Public Class Car
{
int id;
string info;
}
List<Car> cars = {
new Car(1, "[{'color': 'blue','model': 'toyota'}]"),
new Car(2, "[{'color': 'red','model': 'tesla'}]"),
new Car(3, "[{'color': 'green','model': 'honda'}]")
}
I want to return the id(3) of the Honda.
Do I need to convert the whole list to a Json, then query for the specific item.
Or can I do something like
var chosenCar = cars.Where(s => JObject.Parse(s.info)["model"].Value == "honda");

Related

Create a Map of Lists in Flutter

Porting an App from Swift to Flutter. In my App, I have a class, MyClass, and am dealing with a list of about 250 instances. At various times, I need to group the objects based on a particular property.
In Swift, I was able to create a grouped list of my objects like so:
var groupedList = Dictionary<String, Array<MyClass>>()
I was then able to loop through my list of objects, and assign items to the right Array as necessary. I thought it might work to make a Map of Lists in Flutter like this:
Map groupedList = Map<String, List<MyClass>>();
Then I could loop through the items, test the property, create a Map entry for each unique value and append the item to the correct List:
for (var item in listOfObjects) {
if (!groupedList.containsKey(item.someproperty)) {
List<MyClass> sublist = [];
groupedList[item.someproperty] = sublist;
}
groupedList[item.someproperty].add(item);
}
What I get, however, is a Map with all the correct Keys, but each List contains only one instance of MyClass, rather than an actual List of MyClasses.
There's a more succinct syntax using putIfAbsent. This gives the results you expect:
void main() {
var groupedList = <String, List<MyClass>>{};
var listOfObjects = <MyClass>[
MyClass('Europe', 'France'),
MyClass('Europe', 'Germany'),
MyClass('Europe', 'Italy'),
MyClass('North America', 'USA'),
MyClass('Asia', 'Japan'),
MyClass('Asia', 'China'),
];
for (var item in listOfObjects) {
groupedList.putIfAbsent(item.someProperty, () => <MyClass>[]).add(item);
}
print(groupedList);
}
class MyClass {
String someProperty;
String someValue;
MyClass(this.someProperty, this.someValue);
#override
String toString() => '$someProperty->$someValue';
}

How to use JsonConvert.SerializeObject with formatting to add brackets only around CSV values

I have an object that, when converted to a JSON string using the JsonConvert.SerializeObject method, will look like this:
{"01":{"CompanyName":"Hertz","Cars":"Ford, BMW, Fiat"},
"02":{"CompanyName":"Avis","Cars":"Dodge, Nash, Buick"}}
How can I use the Formatting parameter to make the result look like this:
{"01":{"CompanyName":"Hertz","Cars":["Ford", "BMW", "Fiat"]},
"02":{"CompanyName":"Avis","Cars":["Dodge", "Nash", "Buick"]}}
As #dbc mentioned in the comments, you cannot use the Formatting parameter of JsonConvert.SerializeObject to affect whether a particular value in the JSON is surrounded by square brackets or not. The Formatting parameter only controls whether or not Json.Net will add indenting and line breaks to the JSON output to make it easier to read by a human.
In JSON, square brackets are used to denote an array of values, as opposed to a single value. So, if you want to add square brackets for a particular property, the easiest way to do that is to change how that property is declared in your class such that it correspondingly represents an array (or list).
Based on your original JSON, I'm assuming you have a class which looks like this:
public class Company
{
public string CompanyName { get; set; }
public string Cars { get; set; }
}
...and you are creating your JSON something like this:
var results = new Dictionary<string, Company>();
results.Add("01", new Company
{
CompanyName = "Hertz",
Cars = "Ford, BMW, Fiat"
});
results.Add("02", new Company
{
CompanyName = "Avis",
Cars = "Dodge, Nash, Buick"
});
string json = JsonConvert.SerializeObject(results);
To get square brackets in the JSON, change the type of your Cars property from string to List<string>:
public class Company
{
public string CompanyName { get; set; }
public List<string> Cars { get; set; }
}
Of course, you will also need to make a corresponding change to the code which populates the results:
var results = new Dictionary<string, Company>();
results.Add("01", new Company
{
CompanyName = "Hertz",
Cars = new List<string> { "Ford", "BMW", "Fiat" }
});
results.Add("02", new Company
{
CompanyName = "Avis",
Cars = new List<string> { "Dodge", "Nash", "Buick" }
});
string json = JsonConvert.SerializeObject(results);
Here is a short demo: https://dotnetfiddle.net/lgg9jk

JavaFX Sqlite get ID from selected ListView Element

I have a ListView which is filled with artwork names (from SQLite database), these are strings and the names are not primary keys (not unique). Of course each artwork has its own ID (primary key).
What I do, I select one artwork from this list and pass it as a string argument to a button, which creates additional informations (that is not neccessary for this question).
But I select the name, now I need to get the ID from this selected artwork as foreign key.
Of course I can create a select query like this:
"select * from Artwork where Name = ?";
and then get the ID from the artwork with this name, but as I said before, there can be multiple artworks with the same name, so this is not good.
The Plan B which I have is to display in the ListView also the IDs of the the artworks, then If you select one artwork, you could slice the String at " " and take work with the list argument which contains the ID.
But that does not feel right.
Thanks! I hope you understood what I need, if not I could provide code, but there is really a lot.
You are confusing what is displayed in the list view (the data) with how it is displayed (the view). You want the data to consist of objects containing both the id and the name. You want the view to simply display the name of those objects.
Create a class representing the Artwork that contains both the id and the name:
public class Artwork {
private final int id ;
private final String name ;
public Artwork(int id, String name) {
this.id = id ;
this.name = name ;
}
public String getName() {
return name ;
}
public int getId() {
return id ;
}
}
Have your database code return a list of Artwork objects, and define your list view:
ListView<Artwork> listView = new ListView<>();
listView.getItems().addAll(getArtworkFromDatabase());
Finally, to configure how the list view is displayed, set the cell factory:
listView.setCellFactory(lv -> new ListCell<Artwork>() {
#Override
public void updateItem(Artwork artwork, boolean empty) {
super.updateItem(artwork, empty) ;
setText(empty ? null : artwork.getName());
}
}
Now you can get whatever data you need from the selected item:
Artwork selected = listView.getSelectionModel().getSelectedItem();
int selectedId = selected.getId();
String selectedName = selected.getName();

Bind repeater list with enum

I have a requirement where when a user clicks on image a list should be shown with checkboxes and all the categories that is present in DB and user should be able to select the checkboxes. How can this be achieved using asp:repeater control? the caegory is a enum type and can have n number of values. In repeater i have added a checkbox and a label; the label should display the category text.
To start with, you should add the [Description] attribute to each value in your Enum. This allows you to set proper descriptive text for each value. This attribute is in System.ComponentModel, here's an example: -
public enum CalendarShowAsEnum
{
[Description("None")]
None = 10,
[Description("Busy")]
Busy = 20,
[Description("Out Of Office")]
OutOfOffice = 30,
[Description("On Holiday")]
OnHoliday = 40
}
You then need 2 functions: -
One function that takes an Enum type and a ListBox/DropDown as parameters, and adds an entry for each Enum into the list
A helper function that converts the enum into the descriptive title you gave them (example above)
The List function might look as follows (all this is taken from a project I worked on): -
public static void BindNamedEnumList(ListControl list,
Type enumerationType)
{
list.Items.Clear();
Array array = Enum.GetValues(enumerationType);
ListItem item;
string name;
var enumerator = array.GetEnumerator();
if (enumerator != null)
{
while (enumerator.MoveNext())
{
Enum value = enumerator.Current as Enum;
name = EnumHelper.GetEnumName(value);
item = new ListItem(name);
item.Value = Convert.ToInt32(value).ToString();
list.Items.Add(item);
}
}
}
This function takes a Type and a ListControl (which ListBox and DropDownList both inherit from). The Type is the .GetType() of the enum you want to add to the list. Note that it doesn't select any values and that it does depend on each enum value having a defined integer value. The latter part will help you with selecting individual items.
Note the loop calls EnumHelper.GetEnumName(value) - this is the helper function that uses the Description attribute I mentioned at the start. This function looks like: -
public static string GetEnumName(object value)
{
string retVal = string.Empty;
try
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
retVal = ((attributes.Length != 0) ? attributes[0].Description : value.ToString());
}
catch (System.NullReferenceException)
{
}
finally
{
if (string.IsNullOrEmpty(retVal))
{
retVal = "Unknown";
}
}
return retVal;
}
It uses reflection, so you'll need to add an Imports for System.Reflection
To use the list function to bind a set of Enum values to the list, simply call
{HelperClass}.BindNamedEnumList(myListBox, typeof({MyEnumType})

How to serialize dynamic field names using JSON parser

I am using JSON.Net to serialize my objects. For eg, if this is my object
Class MainData
{
[JsonProperty("keyValues")]
string val;
}
the data for 'val' is a key value pair string like this key1:value1.
I have a scenario where I should not get the above 'keyValues' name in my final serialized string and instead get a serialized string which looks like this
{
"key1":"value1"
}
Currently with my serializer I am getting this, which is not what I need
{
"keyValues":"key:value1"
}
Can somebody guide me to any documentation/solution to dynamically assign the name of the field instead of using the default variable name/JSONProperty Name defined inside the object?
Thanks a lot in advance.
I've been struggling with this all day, what I've done is used a dictionary object and serialised this
however I had an error message that was "cannot serialise dictionary", should have read the whole message, "cannot serialise dictionary when the key is not a string or object"
this now works for me and gives me a key/value pair
i have the following objects
public class Meal {
public int mealId;
public int value;
public Meal(int MealId, int Value) {
mealId = MealId;
value = Value;
} }
public class Crew
{
public Meal[] AllocatedMeals {
get {
return new Meal[]{
new Meal(1085, 2),
new Meal(1086, 1) }; } }
public int AllocatedMealTotal {
get {
return this.AllocatedMeals.Sum(x => x.value); } }
}
then the following code
Dictionary<string,string> MealsAllocated = crew.AllocatedMeals.ToDictionary(x => x.mealId.ToString(), x => x.value.ToString());
return new JavaScriptSerializer().Serialize(
new {
Allocated = new {
Total = crew.AllocatedMealTotal,
Values = MealsAllocated } )
to get
"Allocated":{"Total":3,"Values":{"1085":"2","1086":"1"}}

Resources