Search code examples
c#jsonapiviewmodel

How do I populate my model in C# MVC view model with data from C# API JSON?


I wanted to be able to access my data from anywhere so I made a c# data API that returns json for gets and accepts json for posts. All methods use HTTPResponseMessage as a return type so that I can send back the appropriate responses.

In jquery ajax its a simple thing to use and it works great but when I try to use c# mvc I am completely lost where and how to get the data returned from my API into the data model.

I tried using this in my viewModel. It got the data but then what

    static public object GetProfile()
    {
        string url = "http://localhost:50121/api/Profile/1";
        var client = new WebClient();
        var content = client.DownloadString(url);
        var serializer = new JavaScriptSerializer();
        var jsonContent = serializer.Deserialize<object>(content);
        return jsonContent;
    }

    public readonly object d = GetProfile();

Sorry if I am posting this wrong I have not asked questions here a lot.

I just want to populate my model with the json returned from the api call.


Solution

  • This line:

    var jsonContent = serializer.Deserialize<object>(content);
    

    Should be changed to:

    var jsonContent = serializer.Deserialize<YourModelClass>(content);
    

    Where YourModelClass is the model that you want to deserialise into.