MVC3 Convert JSON from REST Service to Model

2019-08-18 11:45发布

问题:

I am trying to implement a remote REST service which is used to handle all logic for my MVC3 web application, and so far I am able to retrieve the serialized object from the webservice, but I am stuck on deserializing the object into my ViewModel to pass to the View.

Here is my controller:

[HttpGet]
public ActionResult Index()
{
    string versions;
    using (var webClient = new WebClient())
    {
        versions = webClient.DownloadString("http://myservice/GetVersions");
    }

    // deserialize JSON/XML somehow...
    //IEnumerable<VersionViewModel> model = ?

    return View(model);
}

What do I need to do to convert the JSON I recieve from the webservice to a ViewModel to render my view? Thanks.

回答1:

You could use RestSharp for the initial request, which should be able to automatically convert the JSON to a suitable data transfer object (DTO). From there, you could use something like AutoMapper to convert from DTO -> ViewModel class.

The DTO (without knowing what your JSON looks like, of course):

public class VersionDto
{
     public string Name { get; set; }
     public string Version { get; set; }
}

The final result something like:

[HttpGet]
public ActionResult Index()
{
    var client = new RestClient ("http://myservice");
    List<VersionDto> versions = client.Execute<List<VersionDto>> (new RestRequest ("/GetVersions"));

    var vms = Mapper.Map<IEnumerable<VersionDto>, IEnumerable<VersionViewModel>> (versions);

    return View(vms);
}

The RestSharp wiki has lots of docs on how it maps the JSON onto your DTO classes, letting you worry less about serialization, and more about your business logic.



回答2:

Just use an XmlSerializer or JsonSerializer and convert the result string to the object. If you google either of those terms you will get lots of hits since its really common. There is even a codeplex project for JSON http://json.codeplex.com/



回答3:

You can simply deserialize with Deserialize() method of JavaScriptSerializer class

JavaScriptSerializer jss = new JavaScriptSerializer();
var versions = jss.Deserialize<IEnumerable<VersionViewModel>>(versions);
return View(versions);