如何从json中获取数据

本文关键字:获取 数据 json | 更新日期: 2023-09-27 18:08:23

可能重复:
如何解析json?

请告诉我在asp.net c#中反序列化json数据的方法。事实上,我有一个json数据,其中有两个对象,比如:

{
    "errstr": "All downloded vedios ",
    "errcode": 0,
    "result": {
        "videos": [
            {
                "id": "22",
                "name": "Ashley",
                "price": "0.49",
                "size": "3712310"
            }
        ],
        "trailer": [
            {
                "id": "1",
                "trailer_name": "charl1",
                "status": "1"
            },
            {
                "id": "2",
                "trailer_name": "charl2",
                "status": "1"
            }
        ]
    }
}

这里我有两个对象视频和预告片。请告诉我在代码中获取这些数据的过程。

如何从json中获取数据

您需要创建一个具有嵌套成员的类例如json文件

{
"GeminiURL":"https://gemini.com/Gemini"
,"Language":"en"
,"Log":{"Debug":true,"Info":true,"Warn":true,"FileName":"d:''temp''tfsgemini.log"}
}

使用c#类进行序列化和反序列化

public class Settings
{
    public string GeminiURL;
    private LogSettings _log;
    public LogSettings Log
    {
        get { return _log = _log ?? new LogSettings(); }
        set { _log = value; }
    }
    public string Language;
    public Settings()
    {
        // defaule settings can be assigned here;
    }
}
public class LogSettings
{
    public bool Debug;
    public bool Info = true;
    public bool Warn = true;
    public string FileName;
}

反序列化代码看起来像:

public static T Load(string fileName)
{
    T t = new T();
        if (File.Exists(fileName))
            t = (new JavaScriptSerializer()).Deserialize<T>(File.ReadAllText(fileName));
        else
            Save(t);
    return t;
}

JSON.NET-http://json.codeplex.com/