You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用JsonTextReader从JSON文件提取指定name、version值的方法

问题原因

你使用的JsonTextReader采用逐令牌顺序解析JSON的模式:当判断reader.Value等于name时,当前命中的是属性名令牌(JsonToken.PropertyName),此时Value存储的就是字段名本身;字段对应的实际值需要再执行一次Read()移动到值令牌才能获取,所以你当前的代码只能输出字段名。

方案1:修正流式读取逻辑(适合大文件场景)

这种方案不需要加载完整JSON结构到内存,适合体积较大的JSON文件,修正后的代码如下:

string fileName = "D:\\Test.json";
string jsonString = File.ReadAllText(fileName);
JsonTextReader reader = new JsonTextReader(new StringReader(jsonString));
string currentPackageName = null;

while (reader.Read())
{
    // 仅在命中属性名令牌时做字段判断
    if (reader.TokenType == JsonToken.PropertyName)
    {
        string propName = reader.Value.ToString();
        if (propName == "name" || propName == "version")
        {
            // 移动游标到当前属性对应的值位置
            reader.Read();
            if (propName == "name")
            {
                currentPackageName = reader.Value?.ToString();
            }
            else
            {
                Console.WriteLine($"包名:{currentPackageName},版本号:{reader.Value}");
            }
        }
    }
}
方案2:反序列化读取(常规场景推荐)

如果JSON文件体积不大,直接反序列化为强类型对象再取值,代码可读性更高、维护成本更低:

  1. 先定义和JSON结构匹配的类(不需要的字段可以省略,反序列化时会自动忽略)
public class InstalledItem
{
    public string name { get; set; }
    public string version { get; set; }
}

public class JsonRoot
{
    public List<InstalledItem> installed { get; set; }
}
  1. 读取和取值代码
string fileName = "D:\\Test.json";
string jsonString = File.ReadAllText(fileName);
var data = JsonConvert.DeserializeObject<JsonRoot>(jsonString);

foreach (var item in data.installed)
{
    Console.WriteLine($"包名:{item.name},版本号:{item.version}");
}

注意:你提供的示例JSON末尾缺少数组和根对象的闭合括号,实际使用时请保证JSON结构完整,否则会触发解析报错。

内容的提问来源于stack exchange,提问作者Jan Schierenbeck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 19:15:42