How to read a JSON file using C #?

0

I have my code that reads an external API and returns me information, I would like to read this information or add it to a class:

I'm using Newtonsoft.Json;

This is Json:

   {
       "success": true,
       "errorMessage": null,
        "answer": {
           "token": "8686330657058660259"
              }
     }



        public class usuario
        {
            public string success { get; set; }
            public string errorMessage { get; set; }
            public List<String> answer { get; set; }
        }




        public string ConsultaUsuario(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "POST";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    username = "sistemacdm",
                    password = "qZrm4Rqk"
                });

                streamWriter.Write(json);
            }

            var response = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                string json = streamReader.ReadToEnd();

                usuario m = JsonConvert.DeserializeObject<usuario>(json);
                string name = m.success;

                return streamReader.ReadToEnd();
            }

        }
  

Error:

     

An exception of type 'Newtonsoft.Json.JsonSerializationException'   occurred in Newtonsoft.Json.dll, but was not processed in   user

     

Additional information: Unable to deserialize the JSON object   current (for example, {"name": "value"}) in type   'System.Collections.Generic.List'1 [System.String]' because the type   requires a JSON array (eg [1,2,3]) to deserialize   correctly.

     

To correct this error, change the JSON to a JSON array (for   example, [1,2,3]) or change the deserialized type so that it is a type   Normal .NET (for example, it is not a primitive type as an integer, nor a   type of collection as an array or list) that can be   deserialized from a JSON object. JsonObjectAttribute too   can be added to the type to force it to deserialize from   a JSON object.

     

Path 'answer.token', line 1, position 54.

    
asked by anonymous 06.12.2017 / 13:21

1 answer

2

To transform a JSON into a C # class you need to use the famous Deserialize . But before that you need to map your class perfectly equal to JSON. Let's take an example using the Json.NET library:

Let's say your JSON is this:

}
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
   'Action',
   'Comedy'
  ]
}

You need to create an identical class to deserialize:

public static class Movie
{
    public string Name { get; set; }
    public Datetime ReleaseDate { get; set; }
    public List<String> Genres { get; set; }
}

Now, to convert your JSON into C # class do:

Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys

Example taken from the library's own website.

NOTE: As Renan replied, if you use RESTSharp , in addition to requesting it, it already deserializes your class. But as the focus of the question is not to make the request and to deserialize I did not find it necessary to explain.

EDIT:

The only thing that is wrong with your code is the class you want to deserialize:

answer It is not a List<String> but an Answer Object. Here is the correction of class usuário :

public class usuario
{
        public string success { get; set; }
        public string errorMessage { get; set; }
        public Answer answer { get; set; }
}

Add in your project the class Answer:

 public class Answer
 {
        public string token { get; set; }
 }
    
06.12.2017 / 13:51