将JSON反序列化为字符串

时间:2012-08-19 08:08:53

标签: c# javascript .net json serialization

如何反序列化:

{
    "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的类实例的属性数据的值。

2 个答案:

答案 0 :(得分: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"]);

答案 1 :(得分: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"]);
}