Deserialize JSON with RESTSharp C#

23,764

Solution 1

Most likely the JSON serializer is failing to deserialize back into objects. It looks like you are trying to combine a VM and DTO into one class which IMO is not a very good idea. Keep the DTO as simple as possible. If you change the EventResponse to the below code can you then get the object?

public class Event
{
    public int id { get; set; }
    public string name { get; set; }
    public string datefrom { get; set; }
    public string timeto { get; set; }
    public string price { get; set; }
    public string imagen { get; set; }
    public string desc { get; set; }
    public string info { get; set; }
    public int user { get; set; }
    public int place { get; set; }
    public string dateto { get; set; }
    public List<object> Eventcategories { get; set; }
}

public class EventResponse
{
    public List<Event> Events { get; set; }
}

Solution 2

You're missing the final step of deserializing the JSON string. You can use Json.net to deserialize the string to the appropriate object. You can do that like so:

var eventResponse = JsonConvert.DeserializeObject<EventResponse>(jsonString);

Here is a link to Newtonsoft's Json.Net http://www.newtonsoft.com/json

Solution 3

This is how you can deserialize directly into an specific entity/object using Newtonsoft.Json.dll, which is a very helpful library and can be installed from nugget. More details you can find on the following link: https://www.nuget.org/packages/Newtonsoft.Json/

userData = JsonConvert.DeserializeObject<GRALUserData>(response.Content,
                    new JsonSerializerSettings
                    {
                        PreserveReferencesHandling = PreserveReferencesHandling.Objects
                    });
Share:
23,764
Pablo Pardo
Author by

Pablo Pardo

Updated on March 31, 2020

Comments

  • Pablo Pardo
    Pablo Pardo over 4 years

    I'm trying to deserialize a JSON in a Xamarin App. I've read a lot about, but still have problems, so, maybe here someone can help:

    My JSON response is something like this:

    {
        "Events":[
                {
                    "id":7,
                    "name":"show",
                    "datefrom":"2012-01-01",
                    "timeto":"12:00:00",
                    "price":"3",
                    "imagen":"null",
                    "desc":"rock band playing",
                    "info":"Info about tickets",
                    "user":1,
                    "place":9,
                    "dateto":"2013-02-02",
                    "timeto":"12:30:00",
                    "Eventcategories":[]
                },
                {"id":2, name:...
    

    As I've read, I've created two classes, one for the Object (Event) and other for the JSON response (EventResponse) The second one has only a list of Events:

    public class EventResponse
    {
        public ObservableCollection<Event> Events { get; set; }
        public EventResponse(){
        }
        }
    }
    

    And Event class has all the fields returned by the JSON:

    private int _id;
            public int id {   
                get { return _id; }
                set {
    
                    _id = value;
                    OnPropertyChanged ();
                }
            }
    
            private string _nombre;
            public string nombre {   
                get { return _nombre; }
                set {
                    if (value.Equals (_nombre, StringComparison.Ordinal))
                        return;
                    _nombre = value;
                    OnPropertyChanged ();
                }
            }...
    

    After this, I want my app to parse this JSON, but the only thing I can get is an String containing the JSON content.

    var client = new RestClient("myip/api/events");
                var request = new RestRequest (Method.GET);
                var asyncHandle = client.ExecuteAsync<EventResponse>(request, response => {
                //Here I see the json result
                string jsonString=response.Content;
                //The same
                Console.WriteLine(response.Content);
                //Nothing is shown here
                Console.WriteLine(response.Data.Events[0].id);
                });
    

    ¿Could anybody give me some clue on how can I see the json result? I think I'm following the appropriate steps, but after many hours I can't reach anything. Thanks

  • SKall
    SKall over 9 years
    RestSharp includes JSON serializer so that is not the root of the problem.
  • SKall
    SKall over 9 years
    RestSharp includes JSON serializer so that is not the root of the problem.
  • Pablo Pardo
    Pablo Pardo over 9 years
    That was exactly the problem. I was making the models by hand, I made it again with this tool: json2csharp.com and now I can parse it without any problem.
  • BardMorgan
    BardMorgan almost 7 years
    In an effort to keep the answer current, I would point out that as of version 103, RestSharp no long contains a dependency on Newtonsoft's JSON.Net.
  • BardMorgan
    BardMorgan almost 7 years
    In an effort to keep the answer current, I would point out that as of version 103, RestSharp no long contains a dependency on Newtonsoft's JSON.Net.
  • Josh
    Josh over 6 years
    That tools saved me as well. Format the c# right and it works! Thanks.