2

我怎样才能反序列化:

{
    "data": [
        {"ForecastID":8587961,"StatusForecast":"Done"},
        {"ForecastID":8588095,"StatusForecast":"Done"},
        {"ForecastID":8588136,"StatusForecast":"Done"},
        {"ForecastID":8588142,"StatusForecast":"Pending"}
    ]
}

class RawData
{
    public string data { get; set; }
}

所以,我只想拥有

[
  {"ForecastID":8587961,"StatusForecast":"Done"},
  {"ForecastID":8588095,"StatusForecast":"Done"},
  {"ForecastID":8588136,"StatusForecast":"Done"},
  {"ForecastID":8588142,"StatusForecast":"Pending"}
]

作为RawData类实例的属性数据的值。

4

2 回答 2

4

使用Json.Net

var obj = (JObject)JsonConvert.DeserializeObject(json);
var newJson = obj["data"].ToString();

或使用内置的JavaScriptSerializer

var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
var newjson = new JavaScriptSerializer().Serialize(dict["data"]);
于 2012-08-19T08:20:48.673 回答
2

将这个 JSON 结构反序列化为:

public class Forecast
{
    public IEnumerable<ForecastData> Data { get; set; }
}

public class ForecastData
{
    public int ForecastID { get; set; }
    public string StatusForecast { get; set; }
}

这对于框架中内置的JavaScriptSerializer类来说非常简单:

string json = "your JSON data here";
IEnumerable<ForecastData> data = new JavaScriptSerializer()
    .Deserialize<Forecast>(json)
    .Data;

或者如果您不想定义模型,您可以这样做:

dynamic result = new JavaScriptSerializer().DeserializeObject(json);
foreach (var item in result["data"])
{
    Console.WriteLine("{0}: {1}", item["ForecastID"], item["StatusForecast"]);
}
于 2012-08-19T09:06:25.153 回答