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.
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
– Harry
@itasouza ready, now I understand the problem, apply EDIT and see if it works
– Leonardo Bonetti
@itasouza if it doesn’t work back here again with the error we make work ;)
– Leonardo Bonetti
Leonardo, it worked, I really appreciate your help!
– Harry
For nothing, after you get the first the sky is the limit ;), I suffered a lot with dehrialization kkk still suffer sometimes... good luck
– Leonardo Bonetti
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
– Harry
Dude, spend about 30 minutes researching how to do this......you explained clearly and objectively.showwwwwwwww
– Rodrigo Storti de Oliveira