Skip to main content
 首页 » 编程设计

c#之从 json 文件中检索项目 c#

2024年02月13日12jackei

{ 
    "_id": "underscore", 
    "_rev": "136-824a0ef7436f808755f0712c3acc825f", 
    "name": "underscore", 
    "description": "JavaScript's functional programming helper library.", 
    "dist-tags": {}, 
    "versions": { 
        "1.0.3": { 
            "name": "xxx", 
            "description": "xxx" 
        }, 
        "1.0.4": {}, 
        "1.1.0": {} 
    } 
} 

我想从 json 文件中检索最新版本 (1.1.0)。但是,它总是给我错误“无法将 json 对象反序列化为 RootObject 类型

这是我的课

public class versions 
{ 
    public string name { get; set; } 
    public string description { get; set; } 
} 
 
public class RootObject 
{ 
    public List<versions> vs { get; set; } 
} 

这里是我使用它的地方

RootObject[] dataset = JsonConvert.DeserializeObject<RootObject[]>(json); 

任何想法。非常感谢

更新:

我已经更新了 JSON 文件格式,但是有些问题..

请您参考如下方法:

我认为问题在于,在 JSON 中您必须引用所有“字段”/属性名称。 (这与标准 Javascript-Notation 不同,在标准 Javascript-Notation 中您可以使用不带引号的属性)。

所以,你的文件应该是这样的:

{ 
  "_id" : "underscore", 
  "versions": { 
    "1.0.3" : { 
       "name": "xxx", 
       "description": "xxx" 
    } 
} 

请注意,{1.0.3: { name: "xxx"} } 也不是有效的 JavaScript,因为“1.0.3”是 JavaScript 中的无效标识符。