Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebAPI 2 Nested JSON

I've been stuck with this for a while and I can't seem to figure it out. Appreciate any help!

This is my model: http://www.jsoneditoronline.org/?id=9ee3466c40627f33c284e63544c8b8a7

I have the proper C# objects set up like this:

public class Media
{
    public string name { get; set; }
    public string title { get; set; }
    public string album { get; set; }
    public string artist { get; set; }
    public string length { get; set; }
    public int bitrate { get; set; }
    public double size { get; set; }
    public string start_time { get; set; }
    public string mimetype { get; set; }
    public string hash { get; set; }
}

public class Playlist
{
    public string name { get; set; }
    public List<Media> media { get; set; }
    public List<Graphics> graphics { get; set; }
    public bool shuffle { get; set; }
    public int volume { get; set; }
    public string start_time { get; set; }
    public string end_time { get; set; }
}

public class Day
{
    public string name { get; set; }
    public List<Playlist> playlists { get; set; }
}


public class Schedule
{
    public List<Day> days { get; set; }
    public string hash { get; set; }
}

I need to POST this whole JSON object directly from the MVC Controller. On other occasions I'd like to PUT the schedule. How can I properly handle this? Examples could really help.

Thanks!

I'm already doing the below for POST:

var schedule = JsonConvert.DeserializeObject<Schedule>(model.ToString());

This is working as expected however, sometimes related Media objects already exist in the database and it is causing an Internal Server Error when trying to INSERT the same Media object (which already exists) - The [Key] for Media is the hash property.

like image 408
user1027620 Avatar asked Dec 12 '15 03:12

user1027620


2 Answers

You need to serialize Day class.

using Newtonsoft.json nuget package you need to serialize it as object. It will automatically serialize complex object to json

List<Day> days = // list of days result
var jsonData= JsonConvert.SerializeObject(days);
return json(jsonData);

Update

As per your update serialize and deserialize functions are working properly. You are facing issue while inserting records in Media. Hash is not unique. and Hash Collision is possible. You need to improve hash generation code to use hash as identical. Useful links to understand hash

like image 64
Bhavik Patel Avatar answered Oct 03 '22 18:10

Bhavik Patel


You can use the extension method AddOrUpdate

using System.Data.Entity.Migrations;

db.Schedule.AddOrUpdate(schedule)
like image 29
Alberto Monteiro Avatar answered Oct 03 '22 19:10

Alberto Monteiro