解析 json 对象

本文关键字:对象 json 解析 | 更新日期: 2023-09-27 18:33:16

我无法理解如何使用Visual .NET将JSON字符串解析为c#对象。任务很简单,但我仍然迷路了...我得到这个字符串:

{"single_token":"842269070","username":"example123","version":1.1}

这是我尝试去消毒的代码:

namespace _SampleProject
{
    public partial class Downloader : Form
    {
        public Downloader(string url, bool showTags = false)
        {
            InitializeComponent();
            WebClient client = new WebClient();
            string jsonURL = "http://localhost/jev";   
            source = client.DownloadString(jsonURL);
            richTextBox1.Text = source;
            JavaScriptSerializer parser = new JavaScriptSerializer();
            parser.Deserialize<???>(source);
        }

我不知道在"<"和">"之间放什么,从我在网上读到的内容来看,我必须为它创建一个新类..?另外,如何获得输出?一个例子会有所帮助!

解析 json 对象

创建一个可以将 JSON 反序列化为的新类,例如:

public class UserInfo
{
    public string single_token { get; set; }
    public string username { get; set; }
    public string version { get; set; }
}
public partial class Downloader : Form
{
    public Downloader(string url, bool showTags = false)
    {
        InitializeComponent();
        WebClient client = new WebClient();
        string jsonURL = "http://localhost/jev";
        source = client.DownloadString(jsonURL);
        richTextBox1.Text = source;
        JavaScriptSerializer parser = new JavaScriptSerializer();
        var info = parser.Deserialize<UserInfo>(source);
        // use deserialized info object
    }
}

如果使用的是 .NET 4 - 请使用动态数据类型。

http://msdn.microsoft.com/en-us/library/dd264736.aspx

string json = "{ single_token:'842269070', username: 'example123', version:1.1}";
     JavaScriptSerializer jss = new JavaScriptSerializer();
     dynamic obj = jss.Deserialize<dynamic>(json);
     Response.Write(obj["single_token"]);
     Response.Write(obj["username"]);
     Response.Write(obj["version"]); 

是的,您需要一个新类,其属性将与您的 JSON 匹配。

MyNewClass result = parser.Deserialize<MyNewClass>(source);

通常的方法是创建一个类(或一组类,用于更复杂的 JSON 字符串),用于描述要反序列化的对象并将其用作泛型参数。

另一种选择是将 JSON 反序列化为Dictionary<string, object>

parser.Deserialize<Dictionary<string, object>>(source);

这样,您可以访问数据,但我不建议您这样做,除非必须这样做。

你需要一个与你正在获取的JSON匹配的类,它将返回该类的新对象,并填充值。

以下是代码。

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
        request = WebRequest.Create("https://myipaddress/api/admin/configuration/v1/conference/1/");
        request.Credentials = new NetworkCredential("admin", "admin123");
        // Create POST data and convert it to a byte array.
        request.Method = "GET";          
                // Set the ContentType property of the WebRequest.
        request.ContentType = "application/json; charset=utf-8";          

        WebResponse response = request.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        JavaScriptSerializer js = new JavaScriptSerializer();
        var obj = js.Deserialize<dynamic>(responseFromServer);
        Label1.Text = obj["name"];
        // Display the content.
        Console.WriteLine(responseFromServer);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();
dynamic data = JObject.Parse(jsString);
var value= data["value"];