Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON with RESTSharp C#

Tags:

json

c#

xamarin

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

like image 283
Pablo Pardo Avatar asked Mar 27 '15 16:03

Pablo Pardo


People also ask

What is C# RestSharp?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.

How do you deserialize a response?

For deserializing the responses, we create a separate class that has the same variables that are present in the JSON response like StatusCode and Message. In the code, we can use this class object to read the JSON response as shown in the example above.

What is Jsonconvert DeserializeObject?

DeserializeObject(String, Type,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter. DeserializeObject(String, Type, JsonSerializerSettings) Deserializes the JSON to the specified .


3 Answers

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

like image 139
SgtRock Avatar answered Nov 10 '22 10:11

SgtRock


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; }
}
like image 29
SKall Avatar answered Nov 10 '22 08:11

SKall


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
                    });
like image 24
Cristina Alboni Avatar answered Nov 10 '22 10:11

Cristina Alboni