curt curt - 3 months ago 18
Dart Question

Can Angular2 Factory fromJson Handle Embedded Fields

I'm trying to flatten foreign key data into a class from a JSON feed. I added the field to the fromJson factory method and it doesn't error out on the browser console(Dartium). When I display it, the field is blank so it looks like it's not getting through, which isn't a surprise. I can't find any documentation on the web for the method. This is my JSON data:

{
"id": 386,
"artist_id": 57,
"label_id": 5,
"style_id": 61,
"title": "A Flower is a Lovesome Thing",
"catalog": "OJCCD-235",
"alternate_catalog": null,
"recording_date": "1957-04-01",
"notes": null,
"penguin": "**(*)",
"category": "jazz",
"label": {
"label_name": "Fantasy"
}
},


This is the method:

factory Record.fromJson(Map<String, dynamic> record) =>
new Record(_toInt(record['id']),
record['title'],
record['catalog'],
record['artist_id'],
record['label_id'],
record['style_id'],
record['alternate_catalog'],
DateTime.parse(record['recording_date']),
record['notes'],
record['penguin'],
record['category'],
record['label_name']
);


This is the invocation:

HttpRequest response = await HttpRequest.request(
url, requestHeaders: headers);
List data = JSON.decode(response.responseText);
final records = data
.map((value) => new Record.fromJson(value))
.toList();
return records;


I've also tried label:label_name in the from Json method. Is it possible to continue to use fromJson to instantiate the object? Is there documentation anywhere that would explain fromJson? I've found some, but it says almost nothing. I'm also looking into flattening it in the Rails serializer or, as a last resort creating a view in the database. As you may notice, I have two other foreigns keys yet to be handled.

Plan B



Günter's answer fixes the problem on the client side. There's also a Rails solution if any one reading would prefer. It requires Active Model Seriializer. Here the pertinent part:

class RecordSerializer < ActiveModel::Serializer
attributes :id, :artist_id, :label_id, :style_id, :title, :catalog, :alternate_catalog,
:recording_date, :notes, :penguin, :category, :label_name
def label_name
object.label.name
end
end


The instruction object.label.name retrieves the name value from the label table. This is the resulting JSON:

{
"id": 386,
"artist_id": 57,
"label_id": 5,
"style_id": 61,
"title": "A Flower is a Lovesome Thing",
"catalog": "OJCCD-235",
"alternate_catalog": null,
"recording_date": "1957-04-01",
"notes": null,
"penguin": "**(*)",
"category": "jazz",
"label_name": "Fantasy"
},

Answer

Not entirely sure I understand the question but I guess this is what you're looking for

record['label']['label_name']
Comments