MVC3 Convert JSON from REST Service to Model

∥☆過路亽.° 提交于 2019-12-25 01:27:27

问题


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);


来源:https://stackoverflow.com/questions/8481366/mvc3-convert-json-from-rest-service-to-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!