how to get Json nested properties to primary one - c#

I have below scenario:
This is my class structure :
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public System.Collections.ObjectModel.Collection<Likes> Likes { get; set; }
}
public class Likes
{
public string Sport { get; set; }
public string Music { get; set; }
public string Food { get; set; }
public string Place { get; set; }
}
When I serialize object of User class then it will generate the below json string :
{"FirstName":"Naresh",
"LastName":"Parmar",
"Likes": [{"Sport":"Cricket",
"Music":"Classic",
"Food":"Gujarati",
"Place":"India"}]
}
I want to generate above json string like below:
{"FirstName":"Naresh",
"LastName":"Parmar",
"Sport":"Cricket",
"Music":"Classic",
"Food":"Gujarati",
"Place":"India"
}
I want the nested properties as primary one.
Any help would be appreciated.
Thanks in advance..
EDIT:
{"FirstName":"Naresh",
"LastName":"Parmar",
"Sport":"Cricket,Chess,Football",
"Music":"Classic",
"Food":"Gujarati",
"Place":"India"
}

It's really bad practice, since the code i'll post bellow doesn't have great maintainability, however if that's what you looking for, you can use this. Another class that have the format that you'd like, and have a method that adds a list of likes to the format you've required. That the class you should serialize to JSON:
class NestedUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Sport { get; set; }
public string Music { get; set; }
public string Food { get; set; }
public string Place { get; set; }
public void AddLikes(System.Collections.ObjectModel.Collection<Likes> likes)
{
foreach (Likes like in likes)
{
Sport += like.Sport + ",";
Music += like.Music + ",";
Food += like.Food + ",";
Place += like.Place + ",";
}
if (Sport != string.Empty)
{
Sport = Sport.Substring(0, Sport.Length - 1);
}
if (Music != string.Empty)
{
Music = Music.Substring(0, Music.Length - 1);
}
if (Food != string.Empty)
{
Food = Food.Substring(0, Food.Length - 1);
}
if (Place != string.Empty)
{
Place = Place.Substring(0, Place.Length - 1);
}
}
}

Since it's not only limited to Likes objects I'd suggest using dynamic objects. So the User class I propose is as follows:
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public dynamic Details { get; set; }
public User()
{
Details = new ExpandoObject();
}
public void AddSingleDetail(string key, string value)
{
var dict = this.Details as IDictionary<string, Object>;
if (dict.ContainsKey(key))
{
dict[key] += "," + value;
}
else
{
dict[key] = value;
}
}
public void AddDetails(object detailsObject)
{
var type = detailsObject.GetType();
foreach (var prop in type.GetProperties())
{
AddSingleDetail(prop.Name, prop.GetValue(detailsObject).ToString());
}
}
}
You can use it for adding single proerpties or adding an object as a whole. I used reflection to get all the property name and values and add them to the user details.
Sample usage:
static void Main(string[] args)
{
var user1 = new User() { FirstName = "Homer", LastName = "Simpson" };
user1.AddSingleDetail("Sport", "Bowling");
user1.AddSingleDetail("Sport", "Sleeping");
user1.AddSingleDetail("Food", "Donut");
user1.AddSingleDetail("Music", "Rock");
string flattenedHomer1 = ConvertUserToFlattenedJson(user1);
var user2 = new User() { FirstName = "Homer", LastName = "Simpson" };
var likes1 = new Likes() { Food = "Donut", Music = "Rock", Place = "Springfield", Sport = "Bowling" };
var likes2 = new Likes() { Food = "Steaks", Music = "Metal", Place = "Evergreen Terrace", Sport = "Sleeping" };
var proStuff = new ProfessionalStuff() { Title = "Boss" };
user2.AddDetails(likes1);
user2.AddDetails(likes2);
user2.AddDetails(proStuff);
string flattenedHomer2 = ConvertUserToFlattenedJson(user2);
}
And the method performing the JSON conversion is:
public static string ConvertUserToFlattenedJson(User u)
{
dynamic flatUser = new ExpandoObject();
flatUser.FirstName = u.FirstName;
flatUser.LastName = u.LastName;
var dict = u.Details as IDictionary<string, Object>;
foreach (var like in dict)
{
((IDictionary<string, Object>)flatUser)[like.Key] = like.Value;
}
string json = Newtonsoft.Json.JsonConvert.SerializeObject(flatUser);
return json;
}
In my sample above user2 is converted to the following JSON string which I believe is what you are looking for:
{
"FirstName": "Homer",
"LastName": "Simpson",
"Sport": "Bowling,Sleeping",
"Music": "Rock,Metal",
"Food": "Donut,Steaks",
"Place": "Springfield,Evergreen Terrace",
"Title": "Boss"
}
While concatenating strings you can check for null or duplicate values. I didn't handle that part.
For the sake of completeness, here's the ProfessionalStuff class I made up:
public class ProfessionalStuff
{
public string Title { get; set; }
}
Hope this helps.

Related

custom response object for model validation in asp.net core

I want custom object in response of API having [required] data annotation on model properties like this:
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "fatal",
"code": "required",
"location": [
"/f:AllergyIntolerance/f:status"
]
}
]
}
Is it possible to do it or I would have to code it.
Because model validation happens before action is called, is there any way I can do it?
To create custom request and respond samples for your api, you can use Swashbuckle.AspNetCore.Swagger and to improve validations on your models you can use FluentValidations Sample. Good Luck!
first for simplify define your models like these :
public class ResponseModel
{
public string resourceType { get; set; }
public List<ResponseIssueModel> issue { get; set; } = new List<ResponseIssueModel>();
}
public class ResponseIssueModel
{
public string severity { get; set; }
public string code { get; set; }
public List<string> locations { get; set; } = new List<string>();
}
Then on your actions you can return this :
var response = new ResponseModel();
response.resourceType = "OperationOutcome";
response.issue.Add(new ResponseIssueModel
{
severity = "fatal",
code = "required",
locations = { "/f:AllergyIntolerance/f:status" }
});
return Ok(response);
you can use Builder Pattern for easy create response object
If you want to validate your model in controller,you could try with TryValidateModel method as mentioned in the document:
I tried as below:
in controller:
var model = new TestModel() { Id=1,nestedModels=new List<NestedModel>() { new NestedModel() { Prop1="P11"} } };
var isvalid=TryValidateModel(model);
var errorfiledlist = new List<string>();
if (!isvalid)
{
foreach (var value in ModelState.Values)
{
foreach (var error in value.Errors)
{
errorfiledlist.Add(MidStrEx(error.ErrorMessage,"The "," field"));
}
}
}
var jsonstring = JsonSerializer.Serialize(model);
foreach (var field in errorfiledlist)
{
var oldstr = String.Format("\"{0}\":null", field);
var newstr = String.Format("\"{0}\":\"required\"", field);
jsonstring = jsonstring.Replace(oldstr, newstr);
};
var obj = JsonSerializer.Deserialize<Object>(jsonstring);
return Ok(obj);
MidStrEx method:
public static string MidStrEx(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
}
return result;
}
Models:
public class TestModel
{
public int Id { get; set; }
[Required]
public string Prop { get; set; }
public List<NestedModel> nestedModels { get; set; }=new List<NestedModel>();
}
public class NestedModel
{
public string Prop1 { get; set; }
[Required]
public string Prop2 { get; set; }
}
The result:

Returning a List<> inheritance C#

class cuentaBancaria
{
public cuentaBancaria()
{
}
public cuentaBancaria(string nombreCliente, string numCuenta, double tipoInteres, double saldo)
{
this.nombreCliente = nombreCliente;
this.numCuenta = numCuenta;
this.tipoInteres = tipoInteres;
this.saldo = saldo;
}
public string nombreCliente { get; set; }
public string numCuenta { get; set; }
public double tipoInteres { get; set; }
public double saldo { get; set; }
public static List<cuentaBancaria> cuentas = new List<cuentaBancaria>()
{
new cuentaBancaria ("John Doe", "123456", 1.5, 159),
new Tarjeta ("John Doe", "123456" , 1.5, 159, "123456789012", "John Doe", TipoTarjeta.CREDITO)
};
}
TipoTarjeta:
enum TipoTarjeta
{
CREDITO,
DEBITO,
MONEDERO,
FINANCIACION
}
Tarjeta:
class Tarjeta : cuentaBancaria
{
public Tarjeta()
{
}
public Tarjeta(string nombreCliente, string numCuenta, double tipoInteres, double saldo, string numTarjeta, string nombre, TipoTarjeta tipoTarjeta)
{
base.nombreCliente = nombreCliente;
base.numCuenta = numCuenta;
base.tipoInteres = tipoInteres;
base.saldo = saldo;
this.numTarjeta = numTarjeta;
this.nombre = nombre;
this.tipoTarjeta = tipoTarjeta;
}
public string numTarjeta { get; set; }
public string nombre { get; set; }
public TipoTarjeta tipoTarjeta { get; set; }
}
I want to return the elements that has a TipoTarjeta.XXX but when I try the
cuentas.Where(c => c.tipoTarjeta == tipo)
I get the error that is an element of the child (Tarjeta) not cuentaBancaria.
How can I only get those elements with that type?
You have a type mismatch.
Your function is declared such that it returns List<cuentaBancaria>, but Where is a LINQ extension method that returns an IEnumerable<cuentBancaria>.
To resolve your issue, add a call to the ToList() extension method as follows:
cuentas.Where(c => c.tipoTarjeta == tipo).ToList()
UPDATE
I copied your code to VSCode and this version of Main works for me. From what I could tell, you needed to reference cuentas through cuentaBancaria; also, the property you were referencing in the Where clause was incorrect, based on the class definition.
public static void Main()
{
var tipo = 3.15;
var result = cuentaBancaria.cuentas.Where(c => c.tipoInteres == tipo).ToList();
foreach (var item in result)
{
Console.WriteLine(item.tipoInteres);
}
}
You first need to filter the list to only the types of Tarjeta, and then you can filter by properties of Tarjeta. You can do this using .OfType<T>() in LINQ:
cuentas.OfType<Tarjeta>().Where(c => c.tipoTarjeta == tipo)

How to encode text using File.WriteAllLines?

I was trying to make a txt file, then rename the extension to .json, I have the encoding step and the WriteAllLines step done, but how do I encode the text?(I have the string needed to write)
Here's the code
string[] lines = { "{", "\"version\": 1,", "\"schema_version\": 2,", "",
$"\"id\": \"{textBox14.Text}\",", "", $"\"title\": \"{textBox7.Text}\",",
$"\"title_localized\": \"{textBox18.Text}\",", "", $"\"artist\": \"{textBox6.Text}\",",
$"\"artist_localized\": \"{textBox8.Text}\",", $"\"artist_source\": \"{textBox9.Text}\",",
$"", $"\"illustrator\": \"{textBox10.Text}\",", $"\"illustrator_source\": \"{textBox11.Text}\",",
$"", $"\"charter\": \"{textBox13.Text}\",", $"", "\"music\": {",
$"\"path\": \"{textBox4.Text}\"", "}", "\"music_preview\": {", $"\"path\": \"{textBox5.Text}\"", "}",
"\"background\": {", $"\"path\": \"{open3.FileName}\"", "}",
"\"charts\": [", "{", "\"type\": \"easy\",", $"\"name\": \"{textBox15.Text}\",",
$"\"difficulty\": {numericUpDown1.Value},", $"\"path\": \"textBox1.Text\"", "},",
"{", "\"type\": \"hard\",", $"\"name\": \"{textBox16.Text}\",", $"\"difficulty\": {numericUpDown2.Value},",
$"\"path\": \"{textBox2.Text}\"", "},", $"]", $"", "}" };
Encoding utf8WithoutBom = new UTF8Encoding(true);
File.WriteAllLines($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", lines);
It was supposed to be something like this:
https://cytoid.io/level.json
Short answer:
Change this:
File.WriteAllLines($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", lines);
to this:
File.WriteAllLines($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", lines, utf8WithoutBom);
Long answer:
You shouldn't be generating JSON like this; you should be using a dedicated serializer. With your current solution, if a user enters an invalid character, your JSON will immediately become invalid. So, as a solution you could use Newtonsoft's JSON.Net. Here is an example:
Class definitions
public class Item
{
public int Version { get; set; }
public int SchemaVersion { get; set; }
public string Id { get; set; }
public string Title { get; set; }
public string TitleLocalized { get; set; }
public string Artist { get; set; }
public string ArtistLocalized { get; set; }
public string ArtistSource { get; set; }
public string Illustrator { get; set; }
public string IllustratorSource { get; set; }
public string Charter { get; set; }
public ItemMusic Music { get; set; }
public ItemMusicPreview MusicPreview { get; set; }
public ItemBackground Background { get; set; }
public List<ItemChart> Charts { get; set; }
}
public class ItemMusic
{
public string Path { get; set; }
}
public class ItemMusicPreview
{
public string Path { get; set; }
}
public class ItemBackground
{
public string Path { get; set; }
}
public class ItemChart
{
public string Type { get; set; }
public string Name { get; set; }
public int Difficulty { get; set; }
public string Path { get; set; }
}
Object initialization and serialization
var item = new Item
{
Version = 1,
SchemaVersion = 2,
Id = textBox14.Text,
Title = textBox7.Text,
TitleLocalized = textBox18.Text,
Artist = textBox6.Text,
ArtistLocalized = textBox8.Text,
ArtistSource = textBox9.Text,
Illustrator = textBox10.Text,
IllustratorSource = textBox11.Text,
Charter = textBox13.Text,
Music = new ItemMusic
{
Path = textBox4.Text
},
MusicPreview = new ItemMusicPreview
{
Path = textBox5.Text
},
Background = new ItemBackground
{
Path = open3.FileName
},
Charts = new List<ItemChart>
{
new ItemChart
{
Type = "easy",
Name = textBox15.Text,
Difficulty = numericUpDown1.Value,
Path = textBox1.Text
},
new ItemChart
{
Type = "hard",
Name = textBox16.Text,
Difficulty = numericUpDown2.Value,
Path = textBox2.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(true));
You could also use an anonymous type instead of creating the full class definition, of course:
var item = new {
Version = 1,
SchemaVersion = 2,
Charts = new List<object>
{
new {
Type = "easy"
}
}
}
and then just serialize this.

Write an Observable Collection to Csv file

I have a datagridview that is bound to an observable collection in a mvvm fashion.
I'm trying to figure out how to write the collection to a csv file.
I can format the headers and get that put in, but not sure how one would iterate over a collection pulling out the values and putting them to a file with comma delimiting.
Here is my class
public class ResultsModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Phone { get; set; }
public string Username { get; set; }
public bool Sucess { get; set; }
public string MessageType { get; set; }
public string SenderMessageSent { get; set; }
public string SenderMessageReceived { get; set; }
}
which gets loaded into an observable collection
Here's a generic helper method which utilizes reflection to get values of all properties in the collection of objects and serializes to comma separated values string. (1 line = 1 object from collection)
public static IEnumerable<string> ToCsv<T>(IEnumerable<T> list)
{
var fields = typeof(T).GetFields();
var properties = typeof(T).GetProperties();
foreach (var #object in list)
{
yield return string.Join(",",
fields.Select(x => (x.GetValue(#object) ?? string.Empty).ToString())
.Concat(properties.Select(p => (p.GetValue(#object, null) ?? string.Empty).ToString()))
.ToArray());
}
}
And the examplary usage:
var oemResultsModels = new List<OemResultsModel>
{
new OemResultsModel
{
FirstName = "Fname1",
LastName = "LName1",
MessageType = "Type1",
Phone = 1234567,
SenderMessageReceived = "something1",
SenderMessageSent = "somethingelse1",
Sucess = true,
Username = "username1"
},
new OemResultsModel
{
FirstName = "Fname2",
LastName = "LName2",
MessageType = "Type2",
Phone = 123456789,
SenderMessageReceived = "something2",
SenderMessageSent = "somethingelse2",
Sucess = false,
Username = "username2"
}
};
using (var textWriter = File.CreateText(#"C:\destinationfile.csv"))
{
foreach (var line in ToCsv(oemResultsModels))
{
textWriter.WriteLine(line);
}
}

Custom Jump lists in Windows Phone

I have been looking at this: http://code.msdn.microsoft.com/wpapps/Custom-LongList-Selector-bf8cb9ad and trying to incorporate into my app. However, its a little confusing since my data is loaded differently. Right now, I have two errors The best overloaded method match for CustomKeyGroup<.ViewModels.SoundData>.GetSoundGroups(System.Collections.Generic.List<.ViewModels.SoundData>)' has some invalid arguments
Argument 1: cannot convert from 'string' to 'System.Collections.Generic.List'
The error is at 'CustomKeyGroup.GetSoundGroups(mvm.Items);' from the mainpage.cs. I know the items is an issue. If you look at the link, they load the data differently w/ listmovie.add.
I know something is screwed up big time but since my data is loaded different, im struggling to get it working correctly.
Id like to have custom jumplist w/ headers by Groups (Alpha, Bravo, etc) located in my SoundModel. Here is a portion:
namespace T.ViewModels
{
public class SoundModel: BindableBase
{
public SoundGroup NewAdds { get; set; }
public SoundGroup Software { get; set; }
}
public bool IsDataLoaded { get; set; }
public void LoadData()
{
// Load data into the model
Software = CreateSoftwareGroup();
NewAdds = CreateNewAddsGroup();
IsDataLoaded = true;
}
private SoundGroup CreateNewAddsGroup()
{
SoundGroup data = new SoundGroup();
data.Title = "New";
string basePath = "assets/audio/newadds/";
data.Items.Add(new SoundData
{
Title = "Test1",
FilePath = basePath + "Test.mp3",
Groups = "Alpha"
});
data.Items.Add(new SoundData
{
Title = "Test2",
FilePath = basePath + "Test2.mp3",
Groups="Bravo"
});
data.Items.Add(new SoundData
{
Title = "Test3",
FilePath = basePath + "Test3.mp3",
Groups= "Zulu"
});
private SoundGroup CreateSoftwareGroup()
{
SoundGroup data = new SoundGroup();
data.Title = "Software";
string basePath = "assets/audio/Software/";
data.Items.Add(new SoundData
{
Title = "Test1",
FilePath = basePath + "Test.mp3",
Groups = "Alpha"
});
data.Items.Add(new SoundData
{
Title = "Test2",
FilePath = basePath + "Test2.mp3",
Groups="Bravo"
});
data.Items.Add(new SoundData
{
Title = "Test3",
FilePath = basePath + "Test3.mp3",
Groups= "Zulu"
});
Here is the relevant mainpage.cs:
SoundData mvm = new SoundData();
this.LongList.ItemsSource = CustomKeyGroup<SoundData>.GetSoundGroups(mvm.Items);
SoundGroup:
{
public class SoundGroup
{
public SoundGroup()
{
Items = new List<SoundData>();
}
public List<SoundData> Items { get; set; }
public string Title { get; set; }
public string Groups { get; set; }
}
}
SoundData :
{
public class SoundData : ViewModelBase
{
public string Title { get; set; }
public string FilePath { get; set; }
public string Items { get; set; }
public string Groups { get; set; }
public RelayCommand<string> SaveSoundAsRingtone { get; set; }
private void ExecuteSaveSoundAsRingtone(string soundPath)
{
App.Current.RootVisual.Dispatcher.BeginInvoke(() =>
{
SaveRingtoneTask task = new SaveRingtoneTask();
task.Source = new Uri("appdata:/" + this.FilePath);
task.DisplayName = this.Title;
task.Show();
}
);
}
public SoundData()
{
SaveSoundAsRingtone = new RelayCommand<string>(ExecuteSaveSoundAsRingtone);
}
}
}
So far from I what can see you should be calling the function as below
SoundModel svm = new SoundModel();
svm.LoadData();
this.LongList.ItemsSource = CustomKeyGroup<SoundData>.GetSoundGroups(svm.Software.Items);
or
this.LongList.ItemsSource = CustomKeyGroup<SoundData>.GetSoundGroups(svm.NewAdds.Items);
the reason is that you need to pass a Generic.List<.ViewModels.SoundData> in method GetSoundGroups and the list is contained in SoundGroup class. Since your data loaded is within SoundModel class so I could probably think of the above implementation only.

Categories