C# to JSON serialization using JSON.Net - json

I have a C# List which looks like this:
var reqUsers = from user in users
select new
{
username = user.username,
firstName = user.firstName,
lastName = user.lastName,
email = user.email
};
I use the below to convert / serialize to JSON ( Newtonsoft.JSON ):
var json = JsonConvert.SerializeObject(reqUsers);
With the above code I get a json string like this:
[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al#test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" } ]
however here is what I need to get : since I am using handlebars templating -
var testdata = {
users: [
{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al#test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" } ]
How can use the Serializer to name the JSON array as above ?

Use:
var json = JsonConvert.SerializeObject(new { users = reqUsers });

use:
var json= new JavaScriptSerializer().Serialize(reqUsers);

Related

Append data to an object upon Sequelize Model Fetch

I have a service function to get users from my MySQL database using Sequelize ORM and i would to like to append fullName to the Users.
const filterUsers = async ([...users]:IUsers[]) => {
let searchAttributes = {};
if (users) { searchAttributes = { [Op.or]: users }; }
const filteredUsers = await User.findAll({
raw: true,
nest: true,
where: { ...searchAttributes },
include: [{
model: Club,
as: 'homeClub',
}, {
model: Club,
as: 'awayClub',
}] });
return filteredUsers as unknown as IUsersWithTeams[];
};
FilteredUsers response:
filteredUsers =
[
{
id: 1
name: 'John',
LastName: 'Mayer',
homeClub: 'Barcelona',
awayClub: 'Real Madrid',
},
{
id: 2,
name: 'Adam',
LastName: 'Smith',
homeClub: 'PSG',
awayClub: 'Milan',
},
]
What i would like to receive:
const expectedUserResponse = [
{
id: 1
name: 'John',
LastName: 'Mayer',
FullName: 'John Mayer',
homeClub: 'Barcelona',
awayClub: 'Real Madrid',
},
{
id: 2,
name: 'Adam',
LastName: 'Smith',
FullName: 'Adam Smith',
homeClub: 'PSG',
awayClub: 'Milan',
},
]
How can i do that ? Thank you very much if you can help me ;)
You need to use a virtual field, see documentation and my other answer to the similar question. It seems the official documentation has the example that perfectly fits your request:
const { DataTypes } = require('#sequelize/core');
const User = sequelize.define('user', {
firstName: DataTypes.TEXT,
lastName: DataTypes.TEXT,
fullName: {
type: DataTypes.VIRTUAL,
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
throw new Error('Do not try to set the `fullName` value!');
}
}
});

NodeJS- ExpressJS mongoose API POST Request with foreign key

I'm trying to create an REST API in JSON. I have 2 models, an business and an address. An Address is part of a business
When I try to create a POST request with the following JSON
{
"name" :"GRIT",
"adress":
{
"street" : "test",
"number": "5",
"city":"leuven",
"postalcode":"2900",
"country":"BEL"
}
}
I get the following error
{
"error": {
"errors": {
"adress": {
"message": "Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "CastError",
"stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\"",
"kind": "ObjectID",
"value": {
"id": "5ad8b5e4ac4b1a443877bfc2",
"street": "test",
"number": "5",
"city": "leuven",
"postalcode": "2900",
"country": "BEL"
},
"path": "adress",
"reason": {
"message": "Cast to ObjectId failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "CastError",
"stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\"",
"kind": "ObjectId",
"value": {
"id": "5ad8b5e4ac4b1a443877bfc2",
"street": "test",
"number": "5",
"city": "leuven",
"postalcode": "2900",
"country": "BEL"
},
"path": "adress"
}
}
},
"_message": "Business validation failed",
"message": "Business validation failed: adress: Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "ValidationError"
}
}
These are my mongoose models
const mongoose = require('mongoose');
const businessSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name:{
type: String,
required: true,
},
adress:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Adress',
required:true
}
});
module.exports = mongoose.model('Business', businessSchema);
const mongoose = require('mongoose');
const adressSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
street:{
type: String,
required: true
},
number:{
type: int,
required: true
},
city:{
type: String,
required: true
},
postalCode:{
type: String,
required: true
},
country:{
type: String,
required: true
}
});
module.exports = mongoose.model('Adress', adressSchema);
The following is my Post request
//POST -> Register a business
router.post('/',function(req,res){
const business = new Business({
id: new mongoose.Types.ObjectId(),
name: req.body.name,
adress:{
id:new mongoose.Types.ObjectId(),
street: req.body.adress.street,
number: req.body.adress.number,
city: req.body.adress.city,
postalcode: req.body.adress.postalcode,
country:req.body.adress.country
}
});
business
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Business created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
module.exports = router;
What did I do wrong? Does the adress doesn't save or do I link the two models wrong with eachother
I am using MongoDB as a Datbase
Take a look at the mongoose docs.
You are trying to set a ObjectId property with an Adress object. What you have to do is first save your adress object, and then reference it inside your business object.
PS: You should name your ids as _id since thats the convention used in MongoDB.
It would look something like this:
let adress = new Adress({
_id: new mongoose.Types.ObjectId(),
street: req.body.adress.street,
number: req.body.adress.number,
city: req.body.adress.city,
postalcode: req.body.adress.postalcode,
country: req.body.adress.country
});
adress
.save()
.then(() => {
let business = new Business({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
adress: adress._id
});
business
.save()
.then((result) => {
console.log(result);
res.status(201).json({
message: "Business created"
});
});
});

Can't show object on Ionic

I have those mock users created:
private mockUsers =
{
"cristian#correo.com": {
name: "Cristian Sures Vera",
gender: "male",
birthday: "1995-12-29",
city: "Telde",
phone: "686722255",
email: "cristian#correo.com",
type: "doctor",
password: "1234"
},
"antonio#correo.com": {
name: "Antonio Perez Perez",
gender: "male",
birthday: "1990-04-22",
city: "Las Palmas",
phone: "444555666",
email: "antonio#correo.com",
type: "patient",
password: "1234",
exercises: {}
}
};
getUsers() {
return this.mockUsers;
}
And I'm trying to show it doing that:
search.html
<ion-searchbar (ionInput)="search($event)" ></ion-searchbar>
<ion-list>
<ion-item *ngFor="let user of users" >
{{user}}
</ion-item>
</ion-list>
search.ts
private users;
constructor(public navCtrl: NavController, public userProvider: UserProvider) {
this.users = userProvider.getUsers();
}
search(event){
this.users = this.userProvider.getUsers();
let val = event.target.value;
if (val && val.trim() != ''){
for (let key in this.users) {
if(searchValueIsInTheUsername(this.users[key])){
return this.users[key];
}
}
}
function searchValueIsInTheUsername(user: any) {
return user['name'].toLowerCase().includes(val.toLowerCase());
}
}
I have to print all the users and cant use *ngFor because is an object and is not supported. Do I have to change the form that I return the object? Or I have another form to show all users within *ngFor?
All the project is public on github on the search-patient branch
It depends on your api return type. If you rest api is returning list of users then it's better to store the Json in the same format. To convert the object to list and to be able to use it, make the following change:
private mockUsers: any[] =
[
"cristian#correo.com": {
name: "Cristian Sures Vera",
gender: "male",
birthday: "1995-12-29",
city: "Telde",
phone: "686722255",
email: "cristian#correo.com",
type: "doctor",
password: "1234"
},
"antonio#correo.com": {
name: "Antonio Perez Perez",
gender: "male",
birthday: "1990-04-22",
city: "Las Palmas",
phone: "444555666",
email: "antonio#correo.com",
type: "patient",
password: "1234",
exercises: {}
},
"another#correo.com": {
name: "Another mock user",
gender: "male",
birthday: "1990-04-22",
city: "Las Palmas",
phone: "444555666",
email: "another#correo.com",
type: "patient",
password: "1234",
exercises: {}
}
] ;

Converting Array to bulk Create in nodejs with Sequelize

This is my req.body json data from angularjs controller:
{
phoneno: [
{ id: 1, gsm: '123457801', firstName: 'Mohamed', lastName: 'Sameer'},
{ id: 2, gsm: '123450987', firstName: 'Hameed', lastName: 'Basha' }
],
sender: 'ifelse',
message: 'Hello Test'
}
i want to get gsm values from req.body
I want to make the above structure into this type:
[{phoneno:123457801;sender:'ifelse';message:'Hello Test'},{phoneno:123450987;sender:ifelse;message:'Hello Test'}]
then only i am able to insert in mysql.
I think it will helpful to you!...
var body={
phoneno: [
{ id: 1, gsm: '123457801', firstName: 'Mohamed', lastName: 'Sameer'},
{ id: 2, gsm: '123450987', firstName: 'Hameed', lastName: 'Basha' }
],
sender: 'ifelse',
message: 'Hello Test'
};
var new_req_body=[];
for(var i=0;i<body.phoneno.length;i++){
var new_arr={
sender:body.sender,
message:body.message,
phoneno:body.phoneno[i].gsm
};
new_req_body.push(new_arr);
}
console.log(new_req_body);

Handlebars nested iteration build-in helper - empty output

I'm trying to use iteration helper inside another one. But the inner helper doesn't output anything.
That's the handlebars template :
{{#people}}
<h4>{{firstName}} {{lastName}}</h4>
{{#students}}
<h3>{{firstName}} {{lastName}}</h3>
{{/students}}
{{/people}}
And that is my JSON :
{
people : [
{ firstName: "Yehuda", lastName: "Katz" },
{ firstName: "Carl", lastName: "Lerche" },
{ firstName: "Alan", lastName: "Johnson" }
],
students: [
{ firstName: "Mike", lastName: "Smith" },
{ firstName: "Dan", lastName: "Knight" },
{ firstName: "Griffin", lastName: "Smith" }
]
}
Whats the solution for this problem?
Try the code online and fast here : http://tryhandlebarsjs.com/
The expression {{#people}}...{{/people}} gives rise to three contexts:
{ firstName: "Yehuda", lastName: "Katz" },
{ firstName: "Carl", lastName: "Lerche" },
{ firstName: "Alan", lastName: "Johnson" }
so there are no students in any of those contexts, which is why the inner expression {{#students}}...{{/students}} gives no output.
Can you elaborate on what it is you are trying to achieve?
Thanks Very much J P....your answer is great...
The right code is :
{
people : [
{ firstName: "Yehuda", lastName: "Katz", students: [{ firstName1: "Mike", lastName1: "Smith"
}] },
{ firstName: "Carl", lastName: "Lerche", students: [{ firstName1: "Mike", lastName1: "Smith"
}] },
{ firstName: "Alan", lastName: "Johnson", students: [{ firstName1: "Mike", lastName1: "Smith"
}] }
],
}