c# - 在 C# 中反序列化 JSON - 有什么问题?
问题描述
我试图在 c# 中反序列化这个 JSON,但没有成功:
{
"settings": {
"path": "http:\/\/www.igormasin.it\/fileuploads\/tanja_23a6id"
},
"files": [{
"file": "\/IMG_0992-Edit_a.jpg"
}, {
"file": "\/IMG_1024-Edit_a.jpg"
}, {
"file": "\/IMG_1074-Edit_a.jpg"
}, {
"file": "\/Untitled-1.jpg"
}]
}
我的代码:
public class JsonTxt
{
public IList<string> settings { get; set; }
public IList<string> files { get; set; }
}
下载字符串包含 Json 文本:
var deserialized = JsonConvert.DeserializeObject<JsonTxt>(downloadString);
Console.WriteLine("*************************************************");
Console.WriteLine(deserialized.settings[0].ToString());
Console.WriteLine(deserialized.files.Count);
例外:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g.
{"name":"value"}) into type 'System.Collections.Generic.IList`1[System.String]' because the type
requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized
type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type
like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also
be added to the type to force it to deserialize from a JSON object.
Path 'settings.path', line 1, position 20.'
我无法理解错误,以及我应该做什么.. 据我了解 IList 是错误的,但还有什么是正确的写法?
解决方案
你的类结构需要是这样的:
public class JsonTxt
{
public Settings Settings { get; set; }
public IList<File> Files { get; set; }
}
public class Settings
{
public string Path { get; set; }
}
public class File
{
public string File { get; set; }
}
Settings
是一个对象,而不是一个集合,并且Files
是一个对象的集合而不是字符串。
推荐阅读
- java - 缩小 WebView 初始比例
- azure - Terraform 参数必须是地图或对象,得到“字符串”
- ionic-framework - 错误 CDVLaunchScreen.storyboard IONIC V1 ON MAC
- python - Python - 有一个函数输出多个数据帧
- java - 在第一次尝试中没有在preparedStatement 中更新ColumnNames
- reactjs - TypeScript/React:“解析错误:意外的令牌”
- android - 如何从 Firebase android kotlin 获取一些子列表?
- perl - 变量不受保护
- javascript - 让“点击”事件侦听器执行的问题
- zerobrane - Zerobrane:无法在 Xubuntu 20.04 上的项目树中右键单击项目