c# - 如何仅解析 json 文件中的值

标签 c# json json.net

从这段代码。我只想解析 json 文件中的值

 if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {                    
                using (StreamReader file = File.OpenText(openFileDialog1.FileName))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    while (reader.Read())
                    {
                        if (reader.Value != null)
                        {
                            richTextBox1.Text = reader.Value.ToString();
                        }
                        else
                        {
                            MessageBox.Show("Error while parsing json file. Please try again.");

                        }
                    }


                }

            }

其值为

 {
"install.and": "a",
"install.emailAddress": "E-mailová adresa",
"install.emailIncorrect": "Zadejte platnou e-mailovou adresu.",
"install.emailRetryPrefix": "Neobdrželi jste e-mail? Zkuste to znovu",
"install.emailRetry": "Zkuste to znovu",
"install.emailSend": "Odeslat odkaz",
"install.emailSent": "E-mail byl odeslán!",
"install.emailSentTo": "E-mail byl odeslán",
"install.emailText1": "Můžete navštívit",
"install.emailText2": "Pokud nám poskytnete e-mailovou adresu, budeme vám moci poslat odkaz na pozdější instalaci.",
"install.installing": "Instalace...",
"install.later": "Instalovat později",
"install.licenseAgreement": "licenční smlouva",
"install.privacyPolicy": "zásady ochrany osobních údajů",
"install.quit": "Ukončit instalační program"
}

我想在 : 符号之后解析它。 (它值吗?)在 richTextbox 中显示为文本。

最佳答案

试试这个代码

using (StreamReader file = File.OpenText(openFileDialog1.FileName))
using (JsonTextReader reader = new JsonTextReader(file))
{
    var o = JObject.Load(reader);
    foreach (var v in o)
    {
        var value = v.Value.Value<string>();
        //do whatever you want with value
    }
}

如果您只想要由换行符连接的值,请尝试这个

using (StreamReader file = File.OpenText(openFileDialog1.FileName))
using (JsonTextReader reader = new JsonTextReader(file))
{
    var o = JObject.Load(reader);
    var e = o.Values().Select(x => x.Value<string>());
    var values = string.Join(Environment.NewLine, e);

    //do whatever you want with values
}

关于c# - 如何仅解析 json 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40231741/

相关文章:

c# - 处理集合时正确使用属性

c# - 字符串未被识别为有效的 DateTime ParseExact

c# - 如何在 Windows 10 通用应用程序中显示模态窗口?

JavaScript/JQuery 从 Web API 检索 JSON 数据

c# - 如何反序列化 JSON 数组并忽略根节点?

c# - Newtonsoft 反序列化向列表添加空值

c# - 在 Visual Studio 2017 的 IServiceCollection 中找不到 AddMvc()

javascript - 提交表单并在没有 jQuery 的情况下获得 JSON 响应

javascript - 从 json 文件读取后检索类型

c# - 无法使用 Json.NET 反序列化具有多个构造函数的类