Answer the question
In order to leave comments, you need to log in
C# WinForms - How to parse json correctly?
I am writing a program with VK Api, I made a GET request, then I had problems with json parsing. When I run the program, nothing is displayed... Here is the code:
public class Account
{
public string id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string bdate { get; set; }
}
private void Example_Load(object sender, EventArgs e)
{
var client = new WebClient();
using (var stream = client.OpenRead("https://api.vk.com/method/users.get?user_ids=210700286&fields=bdate&v=5.64"))
using (var sr = new StreamReader(stream))
{
var text = sr.ReadToEnd();
Account m = JsonConvert.DeserializeObject<Account>(text);
textBox1.Text = m.id;
textBox1.Text += " ";
textBox1.Text += m.first_name;
textBox1.Text += " ";
textBox1.Text += m.last_name;
textBox1.Text += " ";
textBox1.Text += m.bdate;
}
}
Answer the question
In order to leave comments, you need to log in
1. Why use stream when you can use client.DownloadString?
2. The response comes with an array of accounts. That is, you need something like this:
public class Response
{
public List<Account> response { get; set; }
}
public class Account
{
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string bdate { get; set; }
}
...
Response m = JsonConvert.DeserializeObject<Response>(text);
How to parse, I think you will understand from my shit code :)
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using Newtonsoft.Json;
{List<string>Admins = new List<string>();
try
{
JToken fdbdb = JObject.Parse(await Download("https://api.vk.com/method/groups.getById?v=5.64&fields=contacts,deactivated,members_count&group_id=" + GROUPS[K]))["response"];
if (fdbdb[0]["deactivated"] != null)//группа забанена (временно или нет)
{
fuckthewall = true; fuckthetopics = true; isNeedToCheck = false;
}
if (Convert.ToUInt32(fdbdb[0]["members_count"]) < MinimalMembeers)//мало подписчиков
{
fuckthewall = true; fuckthetopics = true; isNeedToCheck = false;
}
JToken GroupContacts = fdbdb[0]["contacts"];
if (GroupContacts == null) GroupContacts = 0;
for (int j = 0; j < GroupContacts.Count(); j++)
{
JToken gjdfj = GroupContacts[j]["user_id"];
if (gjdfj != null) Admins.Add(gjdfj.ToString());
}
}
catch{}
}
{
json = JObject.Parse(await Download("https://api.vk.com/method/wall.get?v=5.64&count=30&owner_id=-" + GROUPS[K]));
if (!json.ToString().Contains("error"))
{
posts = (JArray)json["response"]["items"];
var query = from post in posts
select new
{
id = post["id"],
date = post["date"],
from_id = post["from_id"],//идентификатор автора записи.
text = post["text"],
owner_id = post["owner_id"]//идентификатор владельца стены, на которой размещена запись.
};
int posttobreak = 2;
foreach (var post in query)
{
DateTime Postdate = UnixTimeToDate(Convert.ToDouble(post.date));
if ((DateTimeNow - Postdate).Days < 10 || posttobreak > 0)//проверяем посты не старше 30 дней, но также проверяем парочку
{//первых записей, т.к. закрепленная запись выводится первой и у ней могут быть актуальные комменты, и может быть старше 30 дней, а вторая (по факту самая новая), может быть младше 30 дней
if ((DateTimeNow - Postdate) < c)//если пост опубликован после предыдущей проверки
if (!IsAdmin(Admins, post.from_id.ToString()))//если пост написан не админом
if (Convert.ToInt32(post.from_id) > 0)//проверяем пост на стене
if (post.text.ToString().Length > CommentLen)//если пост содержит текст
//
....
}}}
}
private async Task<string> Download(string whattodownload)
{
string returnstring = "";
using (WebClient w = new WebClient())
{
w.Encoding = Encoding.UTF8;
int ErrorsCount = 0;
bool downloaded = false;
while (downloaded == false)//периодически пытаемся скачать строку
{
try
{
returnstring = await w.DownloadStringTaskAsync(whattodownload);
downloaded = true;
}
catch
{
downloadingErrors++;
downloaded = false; ErrorsCount++; toomanyrequests += 2; Thread.Sleep(2000);
if (ErrorsCount > 10)
{
ErrorsCount = 0;
try
{
using (WebClient w2 = new WebClient())
{
returnstring = await w2.DownloadStringTaskAsync(whattodownload);
downloaded = true; break;
}
}
catch { }
}
}
}
}
try
{
if (returnstring.Contains("Too many requests per second"))//Если в скачанной строке есть ошибка
{
while (returnstring.Contains("Too many requests per second"))//то в цикле пытаемся снова скачать данные пока не скачаем
{
Thread.Sleep(2500); toomanyrequests += 2.5;
using (WebClient w2 = new WebClient())
{
w2.Encoding = Encoding.UTF8;
returnstring = await w2.DownloadStringTaskAsync(whattodownload);
}
}
}
}
catch
{
downloadingErrors++;
using (WebClient w2 = new WebClient())
{
Thread.Sleep(2500); toomanyrequests += 2.5;
w2.Encoding = Encoding.UTF8;
returnstring = await w2.DownloadStringTaskAsync(whattodownload);
}
}
return returnstring;//Если в скачанной строке не было ошибки "Too many requests per second" - все ОК, значит возвращаем ответ сервера
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question