【问题标题】:Deserializing JSON into string array将 JSON 反序列化为字符串数组
【发布时间】:2013-02-01 05:00:54
【问题描述】:

我刚刚开始涉足 C#,并且我一直在研究 JSON 反序列化有一段时间了。我正在使用 Newtonsoft.Json 库。我期待的只是一个字典数组的 json 响应

[{"id":"669","content":" testing","comments":"","ups":"0","downs":"0"}, {"id":"482","content":" test2","comments":"","ups":"0","downs":"0"}]

现在我有:(注意:下载只是一个包含 json 字符串的字符串)

string[] arr = JsonConvert.DeserializeObject<string[]>(download);

我尝试了很多不同的方法,但都失败了。有没有标准的方法来解析这种类型的json?

【问题讨论】:

标签: c# .net json


【解决方案1】:

你有一个 objects 数组而不是字符串。创建一个映射属性并反序列化的类,

public class MyClass {
    public string id { get; set; }
    public string content { get; set; }
    public string ups { get; set; }
    public string downs { get; set; }
}

MyClass[] result = JsonConvert.DeserializeObject<MyClass[]>(download);

JSON 中只有几个基本类型,但是学习和识别它们是有帮助的。对象、数组、字符串等。http://www.json.org/http://www.w3schools.com/json/default.asp 是很好的入门资源。例如,JSON 中的字符串数组看起来像,

["One", "Two", "Three"]

【讨论】:

  • 不客气!除了序列化为强类型类之外,还可以使用JObject.Parse(jsonstring)。这将返回一个 JObject,然后您可以访问 obj.Value&lt;string&gt;("content") 之类的属性。当然,推荐使用强类型方法,但最好知道替代方法 :)
  • @Despertar(下载)究竟代表什么?
  • @Fernando 这是 Chris 使用的变量,它包含需要解析的 json 字符串。
【解决方案2】:

我实现了这一点,希望这对所有人都有帮助。

 var jsonResponse = 
  [{"Id":2,"Name":"Watch"},{"Id":3,"Name":"TV"},{"Id":4,"Name":""}]

 var items = JsonConvert.DeserializeObject<List<MyClass>>(jsonResponse);

其中 MyClass 是实体

 public class MyClass
            {
                public int Id { get; set; }
                public string Name { get; set; }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    相关资源
    最近更新 更多