简体   繁体   English

Json.net读取序列化数组

[英]Json.net reading serialized array

I am trying to read JSON data from web, and i am using Json.net library for this task, the problem is if there is only one json object 我正在尝试从Web读取JSON数据,并且我正在使用Json.net库执行此任务,问题是如果只有一个json对象

{"id":"2340","time":"2014-10-29 16:26:49"}

everything works fine, but if there is an array of them 一切正常,但是如果有它们的话

[{"id":"2340","time":"2014-10-29 16:26:49"}, {"id":"2341","time":"2014-10-29 16:27:21"}]

Program isn't working. 程序无法运行。

using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Collections.Specialized;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;

    namespace Localhostnet
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {

                using (WebClient client = new WebClient())
                {
                    string htmlCode = client.DownloadString('http://localhost/json.php');
                    LocalhostTiming jsonResponse = JsonConvert.DeserializeObject<LocalhostTiming>(htmlCode);
                    string timeId = jsonResponse.id;

                    MessageBox.Show(timeId);
                }
            }
        }

        public class LocalhostTiming
        {
            public string id { get; set; }
            public string time { get; set; }
        }

    }

I've tried to add 我尝试添加

public class DataContainer
{
    public List<LocalhostTiming> LocalhostTiming{ get; set; }
}

But i dont know how to work with this code. 但我不知道如何使用此代码。

You are trying to deserialize an array of LocalhostTiming into one instance of it. 您正在尝试将一组LocalhostTiming反序列化为它的一个实例。 You need to deserialize the object to an array. 您需要将对象反序列化为数组。

List<LocalhostTiming> jsonResponse = JsonConvert.DeserializeObject<List<LocalhostTiming>>(htmlCode);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM