在JSON.NET中反序列化Jarray

时间:2012-10-05 22:22:55

标签: json json.net deserialization

我需要对此进行反序列化。

{"previous_cursor_str":"0","next_cursor":0,"ids":[741999686,240455509,126524150,143548100,124328422,624776268,393738125,587829914,280834485,64818350,282713007,90425850,759794,164401208,114771958,114364910,89725893],"previous_cursor":0,"next_cursor_str":"0"}    

任何想法?

2 个答案:

答案 0 :(得分:4)

它的JObject真的有一个Id的数组。

首先,你可以像这样创建一个代表json的类:

public class RootObject
{
    public string previous_cursor_str { get; set; }
    public int next_cursor { get; set; }
    public List<int> ids { get; set; }
    public int previous_cursor { get; set; }
    public string next_cursor_str { get; set; }
}

然后将json反序列化为对象,执行此操作:

var myJsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);

或者如果您只想在数组中使用ID:

var obj = JObject.Parse(jsonstring);

var idArray = obj["ids"].Children().Select(s=>s.value<string>());

答案 1 :(得分:0)

刚试过https://jsonclassgenerator.codeplex.com/并获得了以下代码。哪个是白色和geepie的类一样。好工具。

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Example
{
  class Result
  {
    [JsonProperty("previous_cursor_str")]
    public string PreviousCursorStr { get; set; }

    [JsonProperty("next_cursor")]
    public int NextCursor { get; set; }

    [JsonProperty("ids")]
    public IList<int> Ids { get; set; }

    [JsonProperty("previous_cursor")]
    public int PreviousCursor { get; set; }

    [JsonProperty("next_cursor_str")]
    public string NextCursorStr { get; set; }
  }    

  public static unsafe void Main()
  {
    Result result = JsonConvert.DeserializeObject<Result> (" ... your string ...");
    Console.WriteLine(result);
  }
}