I'm trying to post JSON to an api through the ember framework, but my api JSON doesnt follow ember conventions. This is what I am trying to post:
[
{
"id": 1,
"name": "Mary Kelly",
"email": "mk#gmail.com",
"subjects": ["1","2"]
}
]
Ember expects this:
{
"user": {
"id": 1
"name": "Mary Kelly",
"subjects": ["1", "2"],
},
"subjects": [{
"id": "1",
"name": "History"
}, {
"id": "2",
"name": "Maths"
}]
}
So, I need a custom serializer in order to make the post, and to do all other CRUD operations. This is what I have:
App.UserSerializer = DS.RESTSerializer.extend({
extractSingle: function(store, type, payload, id, requestType) {
var subjects = payload.subjects,
subjectIds = subjects.mapProperty('id');
var p = {};
p.user = payload;
p.user.subjects = subjectIds;
p.subjects = subjects;
console.log('extractSingle', JSON.stringify(p));
return this._super(store, type, p, id, requestType);
},
extractArray: function(store, type, payload, id, requestType) {
var p = { users: [], subjects: [] };
for (var i = 0; i < payload.length; i++) {
var user = payload[i];
var subjects = user.subjects,
subjectIds = subjects.mapProperty('id');
for (var j = 0; j < subjects.length; j++) {
p.subjects.push(subjects[j]);
}
user.subjects = subjectIds;
p.users.push(user);
}
return this._super(store, type, p, id, requestType);
}
serializeIntoHash: function(hash, type, record, options) {
Ember.merge(hash, this.serialize(record, options));
}
});
extractSingle and extractArray work fine for get requests, but the serializeIntoHash function for posting isn't working for me- can anyone help?
I'm showing it as working, per the serialize hash you've implemented, extraxt* only run on get requests, serializeIntoHash is used for PUT/POST
http://emberjs.jsbin.com/OxIDiVU/58/edit
Related
here i have added the value to the contactList.listChild but the the string list doesn't return all the value to the parent list it only returns the last added value. i know its a simple mistake though i couldn't figure out where am making mistake.
any suggestion would be helpful.
ContactName contactList = new ContactName();
createJson(){
for(int index = 0; index < _contacts.length; index++){
Contact contact = _contacts?.elementAt(index);
List<Item> numbersList = contact.phones.toList();
for(int i = 0; i < numbersList.length; i++ ){
contactList.listChild = [numbersList[i].value];
}
contactList.name = contact.displayName;
lisJson.add(contactList.toJson());
}
var data = {
"data" : lisJson
};
var body = json.encode(data);
print("$body");
}
// here is my model class
class ContactName extends Object {
String name;
List<String> listChild = new List<String>();
Map toJson() => {"name":name, "phone":listChild};
}
this is what am getting from this
{
"data": [
{
"name": "user1",
"phone": [
"8221551458"
]
},
{
"name": "user2",
"phone": [
"1234567890"
]
}
]
}
// and the output should be something like this
{
"data": [
{
"name": "user1",
"phone": [
"8221551458"
]
},
{
"name": "user2",
"phone": [
"8220780548"
"1234567890"
]
}
]
}
You need to replace
contactList.listChild = [numbersList[i].value]
by
contactList.listChild.add(numbersList[i].value)
Your code is creating a new list on every iteration of the for statement, that's why the last element is the only one you see.
Be sure to initialize contactList.listChild before using it or will throw an exception when trying to add a new element.
The following image describes my model relationship between User and Room.
There is a Many to Many relationship between them,
and I have resolved the Self Reference issue by JSON.NET
and adding some configurations to the Application_Start function.
It looks like:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
}
I defined a API like this to return All the users in database as Json.
public ActionResult Index()
{
return Content(JsonConvert.SerializeObject(db.UserSet), "application/json");
}
The point is , when I get a JsonResult , it looks like
(Every "User" has a navigation attribute "Room" )
[
{
"Room": [
{
"User": [
{
"Room": [],
"Id": 3,
"Name": "waterball",
"Account": "pppaass",
"Password": "123"
}
],
"Id": 1,
"Name": "sadafsa"
}
],
"Id": 2,
"Name": "waterball",
"Account": "safasfasd",
"Password": "123"
},
{
"Room": [
{
"User": [
{
"Room": [],
"Id": 2,
"Name": "waterball",
"Account": "safasfasd",
"Password": "123"
}
],
"Id": 1,
"Name": "sadafsa"
}
],
"Id": 3,
"Name": "waterball",
"Account": "pppaass",
"Password": "123"
}, ........
Obviously , the result looks complex ,
How can I get only the Id,Name but NO User attributes of each Room ?
Or what exactly is the common way people handle with this problem?
===========================================================
I have changed my codes to reach my requirement,
but is this actually the common way to resolve this...?
Or does it have some potential problems?
public ActionResult Index()
{
var result = from u in db.UserSet
select new
{
Id = u.Id,
Account = u.Account,
Password = u.Password,
Room = from r in u.Room
select new
{
Id = r.Id,
Name = r.Name
}
};
return Content(JsonConvert.SerializeObject(result), "application/json");
}
I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;
In my node app i pass bunch of queries as Object.I have to form as exact format of request.
Consider my request as:
{q0:{query0},q1:{query1},q2:{query1}}
My reponse should be {q0:{response0},q1{response1},q2{response2}
My actual query(In my app):
{"q0":{"query":"James Madison","type":"/people/presidents","type_strict":"should"},
"q1":{"query":"George Washington","type":"/people/presidents","type_strict":"should"},
"q2":{"query":"John Adams","type":"/people/presidents","type_strict":"should"},
"q3":{"query":"James Monroe","type":"/people/presidents","type_strict":"should"},
"q4":{"query":"Thomas Jefferson","type":"/people/presidents","type_strict":"should"}}
But my response is coming as:
{"result":[q0result,q1result,q3result]}
My code:
for (var id in presidents ) {
var match
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches.push({
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
})
}
callback(matches);
json = JSON.stringify({"result":matches});
res.writeHead(200, {'content-type':'application/json'});
res.end(json);
Please help me to solve this..Thanks in advance.
You are pushing the result in an array instead you should create a property in the result object as below
var matches = {};
for (var id in presidents ) {
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches[id] ={
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
};
}
callback(matches);
I'm trying to get the result below using JsonResult, but I can't
var localJSON = [
{ "id": "1", "label": "tagName1", "value": "tagValue1" },
{ "id": "2", "label": "tagName2", "value": "tagValue2" },
{ "id": "3", "label": "tagName3", "value": "tagValue3" },
{ "id": "1553", "label": "tagName1553", "value": "tagValue1553" }
];
Here is the way I use:
controller
private JsonResult GetAvailableTags()
{
var tagsList = Facade.Tags.Get(CurrentLocale.ID);
var retValue = new
{
id = tagsList.Select(x => x.ID).ToArray(),
label = tagsList.Select(x => x.Name).ToArray(),
value = tagsList.Select(x => x.Name).ToArray()
};
return Json(retValue);
}
public ActionResult AddPhoto()
{
var availblableTags = GetAvailableTags();
JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewBag.AvailableTags = serializer.Serialize(availblableTags.Data);
return View();
}
view
var localJSON = [ #Html.Raw(ViewBag.AvailableTags)];
The result is
var localJSON = [
{"id":[1,2,3,1553],"label":["tagName1","tagName2","tagName3","tagName1553" ],"value":["tagName1","tagName2","tagName3","tagName1553" ]}
];
What should I do to resolve that?
I assume you want to get x.Value for value in JSON? Then change your assignment for retValue to
var retValue = tagsList.Select(
x => new
{
id = x.Id,
label = x.Name,
value = x.Value
}).ToArray();
In your retValue assignment code you were creating a single object of anonymous type with array-typed members id, label and value. For the output you want you need to create an array, each member of which is an object with simple fields id, name and value.