【问题标题】:JSON via c# , extract arrayJSON通过c#,提取数组
【发布时间】:2016-11-22 18:49:58
【问题描述】:

我有一个包含数组的长 JSON。

所有的 JSON 都是动态的,我没有这个 JSON 的 const 结构。

只有我知道“JSON”包含这个数组。

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

我想用 c# 从中提取一个名字的数组。

我尝试这样做但没有成功。

【问题讨论】:

  • 我尝试这样做但没有成功,怎么办?给我们看...
  • 您是否试图避免使用 JavaScriptSerializer?您是否在代码中声明了“员工”类?您应该能够只使用 JavaScriptSerializer 将其解析为“员工”数组,然后获取他们的名字。您编写的任何代码都将很可能重新创建轮子...这是使用标准库反序列化为对象的示例(非常简单):JavaScriptSerializer js = new JavaScriptSerializer(); var empArray= js.Deserialize(employees);... 然后从任何数组中获取名字。

标签: c# arrays json


【解决方案1】:

使用 json.net。反序列化为动态。

dynamic x = JsonConvert.DeserialzeObject(jsonStr);

【讨论】:

    【解决方案2】:

    我通常做的是使用 C# 原生 String.Split 拆分 JSON 字符串

    const string quote = "\""; //You can ignore this line if you like it just adds the "" as a constant string/char value!
    
    string storedValue = "{"firstName":"John", "lastName":"Doe"}" //The JSON value stored either from an HTTPWebRequest or some other method!
    
    string[] str = storedValue.Split(new string[] {quote + "firstName" + quote + ":" }, StringSplitOptions.None); //Split the JSON firstName value!
    

    所以编译器本质上会查找“firstName”:并将 firstName 值与所有其他代码分开,但是如果您执行 str[1],它也会获取 lastName 值,所以我在发送 HTTPWebRequest 后总是这样做从目标服务器接收请求,然后拆分我想要的 ID,然后在“,”处拆分最后一次以从我想要吐出的 JSON 代码中删除姓氏!

    string[] finalSplit = str.Split(new string[] { "," }, StringSplitOptions.None);
    
    string output = finalSplit[0].ToString();
    

    据我所知,“输出”字符串值应该等于 JSON 代码中的“约翰”值!

    如果要删除引号,请使用 C# 中的 Regex.Replace()。

    using System.Net.RegularExpressions; //Import C# library using this code at the top of your class or above the Namespace declaration!
    
    Regex.Replace(output, @quotes, ""); //The 'quotes' method was declared at the top of the first code block it was that code I said you could ignore if you really wanted to!
    

    删除引号后,最后要做的就是将输出放入标签、文本框,甚至可能是使用 System.IO.streamWriter 的文件!

    另外顺便说一句,您如何从文件或通过 HTTPWebRequest 获取 JSON 代码?如果您从 HTTPWebRequest 获取 JSON 代码,我建议将代码转换为 UTF-8 以确保安全!

    现在我知道有一种更正式的方法可以在 C# 中读取 JSON,但这是我的方法,它适用于我,所以如果我有一个同样有效的方法,我认为没有理由使用官方方法,但同样如此只是我的意见! :)

    【讨论】:

    • 不好的方案,就用netwonsoft json.net
    • 好吧,我发现这对我有用,我想我会分享它,看看如果作者想要这样的东西,是否会使用它!
    • 问题是这是一个非常脆弱的解决方案,它不能一概而论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2016-08-19
    • 1970-01-01
    • 2018-12-26
    • 2010-11-24
    • 2020-11-25
    • 1970-01-01
    相关资源
    最近更新 更多