Вот модель, которую я создал для JSON:
Код: Выделить всё
using System;
using System.Collections.Generic;
namespace Test3.Model
{
public class Walks
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("distance")]
public double Distance { get; set; }
[JsonProperty("duration")]
public string Duration { get; set; }
[JsonProperty("difficulty")]
public string Difficulty { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
}
}
Код: Выделить всё
using System;
namespace Test3
{
[AttributeUsage(AttributeTargets.Property)]
public class JsonPropertyAttribute : Attribute
{
public string Key { get; }
public JsonPropertyAttribute(string key)
{
Key = key;
}
}
}
Код: Выделить всё
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Test3
{
public class GenericJsonParser
{
public static List ParseJson(string json) where T : new()
{
// Logic for parsing JSON...
}
private static T ParseSingleObject(string json) where T : new()
{
// Logic for parsing a single JSON object...
}
private static void SetPropertyValue(T obj, string key, string value)
{
// Logic to set property value using reflection...
}
}
}
Код: Выделить всё
{
"walks": [
{
"id": 1,
"name": "River Walk",
"distance": 5.5,
"duration": "2 hours",
"difficulty": "Easy",
"description": "A scenic walk along the river with beautiful views."
},
{
"id": 2,
"name": "Mountain Trail",
"distance": 10.2,
"duration": "4 hours",
"difficulty": "Moderate",
"description": "A challenging trail through the mountains."
},
{
"id": 3,
"name": "Forest Loop",
"distance": 3.8,
"duration": "1 hour",
"difficulty": "Easy",
"description": "A peaceful walk through the forest."
}
]
}
Когда я пытаюсь проанализировать JSON, я могу получить только пустой список прогулок.
Я не уверен, правильно ли моя логика синтаксического анализа сопоставляет свойства с ключами JSON с помощью JsonPropertyAttribute.
Код: Выделить всё
string json = File.ReadAllText("path_to_your_json_file");
List walksList = GenericJsonParser.ParseJson(json);
Эта структура должна предоставлять достаточный контекст, чтобы другие могли понять вашу ситуацию и предложить соответствующую помощь. Прежде чем запускать анализатор, обязательно укажите реальный путь к файлу JSON и убедитесь, что он правильно отформатирован.
Подробнее здесь: https://stackoverflow.com/questions/790 ... t-external