简体   繁体   English

C#无法反序列化当前的JSON对象

[英]c# Cannot deserialize the current JSON object

Trying to get JSON data from ThingSpeak however getting the above error, works well with JSON placeholder as the URL. 尝试从ThingSpeak获取JSON数据,但遇到上述错误,将JSON占位符用作URL效果很好。

Here is my main cs code: 这是我的主要CS代码:

namespace Drip
{
    public class Feed
    {
        public DateTime Created_at { get; set; }
        public int Entry_id { get; set; }
        public string Field1 { get; set; }
    }

    public partial class DripPage : TabbedPage
    {
        private const string Url = "https://thingspeak.com/channels/301726/field/1.json";
        private HttpClient _client = new HttpClient();
        private ObservableCollection<Feed> _data;

        public DripPage()
        {
            InitializeComponent();
        }

        protected override async void OnAppearing()
        {
            var content = await _client.GetStringAsync(Url);
            var data = JsonConvert.DeserializeObject<List<Feed>>(content);

            _data = new ObservableCollection<Feed>(data);
            postsListView.ItemsSource = _data;
            base.OnAppearing();
        }

Here is my JSON: 这是我的JSON:

{
  "channel": {
    "id": 301726,
    "name": "Testing ESP8266",
    "description": "Water meter pulse count",
    "latitude": "0.0",
    "longitude": "0.0",
    "field1": "Water Pulse",
    "created_at": "2017-07-12T12:19:38Z",
    "updated_at": "2017-09-26T08:41:17Z",
    "elevation": "54",
    "last_entry_id": 151
  },
  "feeds": [
    {
      "created_at": "2017-08-15T13:14:28Z",
      "entry_id": 52,
      "field1": "13.00\r\n\r\n"
    },
    {
      "created_at": "2017-08-15T13:14:44Z",
      "entry_id": 53,
      "field1": "13.00\r\n\r\n"
    },
    {
      "created_at": "2017-08-15T13:14:59Z",
      "entry_id": 54,
      "field1": "13.00\r\n\r\n"
    }
  ]
}

The returned json is not an array, so it can't be deserialized as a List<Feed> , hence an exception is thrown. 返回的json不是数组,因此不能将其反序列化为List<Feed> ,因此会引发异常。 It is an object , and one of that object's members is the array that you are interested in. The backing C# class to deserialize should have the following members: 它是一个对象 ,并且该对象的成员之一是您感兴趣的数组。要反序列化的支持C#类应具有以下成员:

public class RootObject
{
    public Channel channel { get; set; }
    public List<Feed> feeds { get; set; }
}

public class Channel
{
    public int id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string latitude { get; set; }
    public string longitude { get; set; }
    public string field1 { get; set; }
    public DateTime created_at { get; set; }
    public DateTime updated_at { get; set; }
    public string elevation { get; set; }
    public int last_entry_id { get; set; }
}

public class Feed
{
    public DateTime created_at { get; set; }
    public int entry_id { get; set; }
    public string field1 { get; set; }
}

Instead of deserializing to a List<Feed> , you would deserialize to a RootObject (or whatever you choose to call it): 不用反序列化为List<Feed> ,您可以反序列化为RootObject (或任何您选择调用的对象):

var data = JsonConvert.DeserializeObject<RootObject>(content);
_data = new ObservableCollection<Feed>(data.feeds);

try this maybe it will work fine for you first: place this code on your activity and instanciate all var;you will create a javalist to deserialize your json, then you will the method webclient to get your json, then you will use the method runonuithread to excute the process in background. 尝试一下,也许首先适合您:将这段代码放在您的活动上并实例化所有var;您将创建一个Javalist来反序列化json,然后将使用webclient方法获取json,然后将使用runonuithread方法在后台执行该过程。

articles = new JavaList<RootObject>();
        mWebClient = new WebClient();
        mUrl = new Uri(urlAddress);
        mWebClient.DownloadDataAsync("https://thingspeak.com/channels/301726/field/1.json");
        mWebClient.DownloadDataCompleted += MWebClient_DownloadDataCompleted;

second: the method mWebClient.DownloadDataCompleted will generate this : 第二:方法mWebClient.DownloadDataCompleted将生成以下内容:

private void MWebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        RunOnUiThread(() =>
        {
            try
            {
                string json = Encoding.UTF8.GetString(e.Result);
                articles = JsonConvert.DeserializeObject<JavaList<RootObject>>(json);
                mAdapter = new ArticleAdapterCostum(this, articles);
                mListView.Adapter = mAdapter;
            }
            catch (Exception exception)
            {
                Toast.MakeText(this, " Vueillez verifier votre connexion a internet puis reessayer ", ToastLength.Short).Show();
            }
        });
    }

don't forget to create a costum adapter to your listview. 不要忘记为您的列表视图创建一个Costum适配器。

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

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