U
U
U_n_d_e_r2021-03-07 17:04:13
JSON
U_n_d_e_r, 2021-03-07 17:04:13

How to properly deserialize JSON?

I create 2 files, one with a request, the second with processing.

using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Collections.Generic;
using Newtonsoft.Json;
using appcosnole;

namespace Project
{

public class NewBaseType

{

static void Main(string[] args)
{
try{
string url = "https://randomuser.me/api/";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string response ;
using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}


Login myDeserializedClass = JsonConvert.DeserializeObject<Login>(response);
Console.WriteLine(myDeserializedClass.username); 
}
catch{

} 
}

}
}

Второй файл:using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace appcosnole
{
public class Login
{
public string uuid { get; set; }
public string username { get; set; }
public string password { get; set; }
public string salt { get; set; }
public string md5 { get; set; }
public string sha1 { get; set; }
public string sha256 { get; set; }
}
}


Instead of a clear answer, an empty line pops up.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
leschikov, 2021-03-07
@U_n_d_e_r

Add

public class Result
    {
        public Login login { get; set; }
    }

and fix it
Login myDeserializedClass = JsonConvert.DeserializeObject<Result>(response).login;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question