I thought I would understand Json.NET now a bit
but unfortunately not. Can somebody help me with that
I am trying to show data from the json-file in the Console
(Error:CS1061 | List has no definition for "title" | file:Programm.cs | line: 23)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var todos = CObject();
if (todos != null)
{
Console.WriteLine(todos.title);
Console.ReadKey();
}
}
static List<Todos> CObject()
{
string localfile =
@"C:\g\todos.json";
if(File.Exists(localfile))
{
var todos =
JsonConvert.DeserializeObject<List<Todos>>
(File.ReadAllText(localfile));
return todos;
}
string urlfile = new WebClient().DownloadString(
"https://jsonplaceholder.typicode.com/todos");
if (File.Exists(urlfile))
{
var todos =
JsonConvert.DeserializeObject<List<Todos>>
(File.ReadAllText(urlfile));
return todos;
}
return null;
}
}
}
This is the Todos.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
[Serializable]
public class Todos
{
public byte userId { get; set; }
public ushort id { get; set; }
public string title { get; set; }
public bool completed { get; set; }
}
}
The json-file looks something like that:
[
{
"userId": 1,
"id": 19,
"title": "molestiae ipsa aut voluptatibus pariatur dolor nihil",
"completed": true
},
{
"userId": 1,
"id": 20,
"title": "ullam nobis libero sapiente ad optio sint",
"completed": true
}
]
CodePudding user response:
CObject
returns a List (btw naming the class Todo
would probably be better for later understanding). You can iterate over the list and each item inside should have a title property. But a list has not.
foreach(var item in todos) {
Console.WriteLine(item.title);
}