You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用WinForms+C#读取Firebase数据遇Json序列化错误求助

问题:WinForms+C#读取Firebase数据时Json序列化失败

错误信息

Newtonsoft.Json.JsonSerializationException: 'Error converting value "Could not parse auth token." to type 'valuesClass''

场景说明

树莓派端Python程序已成功将数据写入Firebase的values节点(子节点为sarj、gyro),但WinForms+C#程序读取数据同步到GUI时失败。曾怀疑字符串值导致问题,改为整数类型后仍出现其他错误。


C#程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Newtonsoft.Json;
using FireSharp;
using FireSharp.Config;
using FireSharp.Response;
using FireSharp.Interfaces;

namespace databaseGUI
{
    public partial class Form1 : Form
    {
        IFirebaseConfig config = new FirebaseConfig
        {
            // 已反复核对配置信息
            BasePath = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            AuthSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        };
        
        IFirebaseClient client;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            client = new FireSharp.FirebaseClient(config);
            if (client != null)
            {
                MessageBox.Show("Connected");
            }
        }

        private void RTBButton_Click(object sender, EventArgs e)
        {
            FirebaseResponse response = client.Get(@"values");
            Dictionary<string, valuesClass> data = JsonConvert.DeserializeObject<Dictionary<string, valuesClass>>(response.Body.ToString());
            PopulateRTB(data);
        }

        private void dataView_Click(object sender, EventArgs e)
        {
            FirebaseResponse response = client.Get(@"values");
            Dictionary<string, valuesClass> data = JsonConvert.DeserializeObject<Dictionary<string, valuesClass>>(response.Body.ToString());
            PopulateDataView(data);
        }

        private void PopulateRTB(Dictionary<string, valuesClass> record)
        {
            richTextBox1.Clear();
            foreach (var item in record)
            {
                richTextBox1.Text += item.Key + "\n";
                richTextBox1.Text += item.Value.gyroData + "\n";
                richTextBox1.Text += item.Value.sarjData + "\n";
            }
        }

        private void PopulateDataView(Dictionary<string, valuesClass> record)
        {
            dataGridView1.Rows.Clear();
            dataGridView1.Columns.Clear();

            dataGridView1.Columns.Add("gyrodata", "Gyro");
            dataGridView1.Columns.Add("sarjdata", "Sarj");

            foreach (var item in record)
            {
                dataGridView1.Rows.Add(item.Key, item.Value.gyroData, item.Value.sarjData);
            }
        }
    }
}

数据类

namespace databaseGUI
{
    class degerlerClass
    {
        public string gyroData { get; set; }
        public string sarjData { get; set; }
    }
}

Python程序

import smbus
import time
from pyrebase import pyrebase
import sys

config = {
    "apiKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "authDomain": "xxxxxxxxxxxxxxxxxxxxxxx.com",
    "databaseURL": "https://xxxxxxxxxxxxxxx.firebaseio.com",
    "storageBucket":"" 
}

firebase = pyrebase.initialize_app(config)
db = firebase.database()

data = {"sarj": str(10), "gyro": str(5) }
db.child("values").set(data)

print(data)

解决步骤

1. 修复认证错误

错误信息"Could not parse auth token."说明FireSharp的认证配置存在问题:

  • 确认BasePath是Firebase数据库的完整URL(必须以https://开头,结尾不带斜杠)
  • 确认AuthSecret是Firebase项目的数据库秘密(在Firebase控制台 → 项目设置 → 服务账号 → 数据库秘密中获取,注意不是API Key)

2. 修正数据类与Firebase节点名匹配

Python写入的节点是sarj和gyro,但C#数据类的属性是gyroData和sarjData,字段名不匹配会导致序列化失败。同时原代码中类名定义为degerlerClass,但实际使用的是valuesClass,类名不统一也会报错。修改数据类如下:

namespace databaseGUI
{
    class valuesClass
    {
        [JsonProperty("gyro")]
        public string gyroData { get; set; }
        
        [JsonProperty("sarj")]
        public string sarjData { get; set; }
    }
}

3. 修正数据读取与序列化逻辑

Firebase中values节点的结构是直接包含sarj和gyro字段,而非字典结构,因此不需要反序列化为Dictionary<string, valuesClass>,直接反序列化为单个valuesClass对象即可:

// 修改RTBButton_Click方法
private void RTBButton_Click(object sender, EventArgs e)
{
    try
    {
        FirebaseResponse response = client.Get(@"values");
        valuesClass data = JsonConvert.DeserializeObject<valuesClass>(response.Body.ToString());
        richTextBox1.Clear();
        richTextBox1.Text += $"gyro: {data.gyroData}\n";
        richTextBox1.Text += $"sarj: {data.sarjData}\n";
    }
    catch (Exception ex)
    {
        MessageBox.Show($"读取失败: {ex.Message}\n{ex.InnerException?.Message}");
    }
}

// 修改dataView_Click方法
private void dataView_Click(object sender, EventArgs e)
{
    try
    {
        FirebaseResponse response = client.Get(@"values");
        valuesClass data = JsonConvert.DeserializeObject<valuesClass>(response.Body.ToString());
        dataGridView1.Rows.Clear();
        dataGridView1.Columns.Clear();

        dataGridView1.Columns.Add("gyrodata", "Gyro");
        dataGridView1.Columns.Add("sarjdata", "Sarj");
        dataGridView1.Rows.Add(data.gyroData, data.sarjData);
    }
    catch (Exception ex)
    {
        MessageBox.Show($"读取失败: {ex.Message}\n{ex.InnerException?.Message}");
    }
}

4. 调试辅助

在读取数据时先打印响应内容,确认返回的是正确数据而非错误信息,便于快速定位问题:

Console.WriteLine(response.Body);

内容的提问来源于stack exchange,提问作者demolished

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:17:00