0

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

{"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.

1 Answer 1

2

You are trying to deserialize an array of LocalhostTiming into one instance of it. You need to deserialize the object to an array.

List<LocalhostTiming> jsonResponse = JsonConvert.DeserializeObject<List<LocalhostTiming>>(htmlCode);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.