How to read a JSON file using C#?

Asked

Viewed 1,370 times

1

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

I’m using Newtonsoft.Json;

This the 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 the code of user

Additional Information: Unable to deserialize JSON object current (e.g., {"name": "value"}) in type 'System.Collections.Generic.List`1 [System.String]' because the type requires a JSON matrix (e.g., [1 , 2,3]) to deserialize correctly.

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

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

1 answer

5


To turn a JSON into class c# you need to use the famous Deserialize. But before that you need to map your class perfectly the same as JSON. Let’s look at an example using the library Json.NET:

Let’s say your JSON is this:

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

You need to create a class identical to the same to be able 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 to C# Class do:

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

Example taken from the library’s own website.

NOTE: How Renan answered, if you use the Restsharp, In addition to making the requisition he already deserializes his class. But as the focus of the question is not to make the request and already deserializar did not find it necessary to explain.

EDIT:

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

answer Is not a List<String> yes an Answer Object. Follows class correction usuário:

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

Add the Answer class to your project:

 public class Answer
 {
        public string token { get; set; }
 }
  • Leonardo, your answer almost worked, I’m already using Newtonsoft.Json; , see in my question, the structure is equal to your example, but it did not work, give an error when you will read the token

  • @itasouza ready, now I understand the problem, apply EDIT and see if it works

  • @itasouza if it doesn’t work back here again with the error we make work ;)

  • Leonardo, it worked, I really appreciate your help!

  • For nothing, after you get the first the sky is the limit ;), I suffered a lot with dehrialization kkk still suffer sometimes... good luck

  • I’m doing this for the first time, so I’m picking up, to top it off, I just did the first part that would be to pick up the token, The example they posted didn’t help much: https://answall.com/questions/260751/d%C3%Bavida-com-webrequest-m%C3%A9todo-get-passing-token

  • Dude, spend about 30 minutes researching how to do this......you explained clearly and objectively.showwwwwwwww

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.