Member 9992334 Ответов: 0

Как десериализовать большой и сложный json


Hi,
I am a real API newbie  and I need to deserialize a  quite complex Json from an IOT provider but I am stuck from long time on this issue:
With the attached code I get strange results : I get Network.name instead than expected Unit.name. 
Furthermore:  Unit is supposed to be an array but if I try to deserialize it as array I get the exception: "Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Web_request.API_BBL+Unit]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly."
Classes was generated with paste as Json Classes Vb.net function.
Thanks so much for any kind advise, all the best

link to json file: https://drive.google.com/open?id=1kXYcoSJE-aAJWX1WR6wjOB4r6AFikhRh


Что я уже пробовал:

Imports System
Imports System.Dynamic
Imports System.Text
Imports System.IO
Imports System.Net.Http
Imports System.Threading.Tasks
Imports RestSharp.Authenticators
Imports Web_request
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports RestSharp





Public Class API_BBL

    Public Class Rootobject
        Public Property id As String
        Public Property revision As Integer
        Public Property generation As Integer
        Public Property lastUsedProtocol As Integer
        Public Property channels As Integer
        Public Property mode As Integer
        Public Property grade As Integer
        Public Property uuid As String
        Public Property gateway As Gateway
        Public Property email As String
        Public Property name As String
        Public Property visitorKey As String
        Public Property managerKey As String
        Public Property type As Integer
        Public Property nextSceneID As Integer
        Public Property nextUnitID As Integer
        Public Property nextEventID As Integer
        Public Property nextControlID As Integer
        Public Property nextGroupID As Integer
        Public Property protocolVersion As Integer
        Public Property allUnitPosition As Integer
        Public Property nearUnitPosition As Integer
        Public Property nearbyEnabled As Boolean
        Public Property allowPrototypes As Boolean
        Public Property longitude As Single
        Public Property latitude As Single
        Public Property timeZone As String
        Public Property settings As Settings
        Public Property grid As Grid
        Public Property photos() As Photo
        Public Property units() As Unit
        Public Property scenes() As Scene
        Public Property events() As _Event
        Public Property circadianProfiles() As Circadianprofile
    End Class

    Public Class Gateway
    End Class

    Public Class Settings
        Public Property revision As Integer
        Public Property control As Control
    End Class

    Public Class Control
        Public Property useLastLevels As Boolean
        Public Property enabled As Boolean
        Public Property activateTimersAfterStartup As Boolean
        Public Property startupDuration As Integer
        Public Property tapDuration As Integer
        Public Property dimDuration As Integer
        Public Property fadeout As Integer
        Public Property behaviour As Integer
        Public Property weekdays() As Weekday
    End Class

    Public Class Weekday
        Public Property weekday As Integer
        Public Property dayStart As Integer
        Public Property dayEnd As Integer
        Public Property dayTimeout As Integer
        Public Property nightTimeout As Integer
    End Class

    Public Class Grid
        Public Property type As Integer
        Public Property position As Integer
        Public Property groupID As Integer
        Public Property cells() As Cell
    End Class

    Public Class Cell
        Public Property type As Integer
        Public Property position As Integer
        Public Property groupID As Integer
        Public Property unit As Integer
    End Class

    Public Class Photo
        Public Property position As Integer
        Public Property height As Single
        Public Property controls() As Object
        Public Property image As String
    End Class

    Public Class Unit
        Public Property deviceID As Integer
        Public Property address As String
        Public Property cpu As Integer
        Public Property name As String
        Public Property type As Integer
        Public Property appearance As Integer
        Public Property hueID As Integer
        Public Property groupID As Integer
        Public Property position As Integer
        Public Property revision As Integer
        Public Property configRevision As Integer
        Public Property firmware As Integer
        Public Property modes() As Mode
        Public Property smartSwitch As Smartswitch
        Public Property pushButtonToggleDisabled As Boolean
        Public Property presenceSensor As Presencesensor
        Public Property linkedSensor As Integer
        Public Property gain As Single
        Public Property startupMode As Integer
        Public Property minOnLevel As Single
        Public Property minLevel As Single
        Public Property maxLevel As Single
        Public Property parameters() As Object
        Public Property sequenceCounter As Integer
        Public Property behaviour As Integer
        Public Property timeout As Integer
        Public Property labels As Labels
        Public Property details As Details
        Public Property actionConfig As Integer
        Public Property actions() As Object
        Public Property pushButton As Pushbutton
        Public Property switchConfig As Switchconfig
        Public Property securityKey As String
        Public Property pushButton2 As Pushbutton2
        Public Property pushButton3 As Pushbutton3
        Public Property pushButton4 As Pushbutton4
    End Class

    Public Class Smartswitch
        Public Property type As Integer
        Public Property id As Integer
        Public Property scenes() As Object
        Public Property scenes2() As Object
        Public Property group As Integer
        Public Property unit As Integer
        Public Property lingerTime As Integer
        Public Property fadeTime As Integer
        Public Property excludeOFF As Boolean
        Public Property index As Integer
    End Class

    Public Class Presencesensor
        Public Property type As Integer
        Public Property id As Integer
        Public Property scenes() As Object
        Public Property scenes2() As Object
        Public Property group As Integer
        Public Property unit As Integer
        Public Property lingerTime As Integer
        Public Property fadeTime As Integer
        Public Property excludeOFF As Boolean
        Public Property index As Integer
    End Class

    Public Class Labels
    End Class

    Public Class Details
    End Class

    Public Class Pushbutton
        Public Property type As Integer
        Public Property id As Integer
        Public Property scenes() As Integer?
        Public Property scenes2() As Object
        Public Property group As Integer
        Public Property unit As Integer
        Public Property lingerTime As Integer
        Public Property fadeTime As Integer
        Public Property excludeOFF As Boolean
        Public Property index As Integer
    End Class

    Public Class Switchconfig
        Public Property buttons() As Button
        Public Property switches() As Object
        Public Property exclusiveScenes As Boolean
        Public Property longPressAllOff As Boolean
        Public Property toggleDisabled As Boolean
    End Class

    Public Class Button
        Public Property type As Integer
        Public Property action As Integer
        Public Property target As Integer
    End Class

    Public Class Pushbutton2
        Public Property type As Integer
        Public Property id As Integer
        Public Property scenes() As Object
        Public Property scenes2() As Object
        Public Property group As Integer
        Public Property unit As Integer
        Public Property lingerTime As Integer
        Public Property fadeTime As Integer
        Public Property excludeOFF As Boolean
        Public Property index As Integer
    End Class

    Public Class Pushbutton3
        Public Property type As Integer
        Public Property id As Integer
        Public Property scenes() As Integer
        Public Property scenes2() As Object
        Public Property group As Integer
        Public Property unit As Integer
        Public Property lingerTime As Integer
        Public Property fadeTime As Integer
        Public Property excludeOFF As Boolean
        Public Property index As Integer
    End Class

    Public Class Pushbutton4
        Public Property type As Integer
        Public Property id As Integer
        Public Property scenes() As Integer
        Public Property scenes2() As Object
        Public Property group As Integer
        Public Property unit As Integer
        Public Property lingerTime As Integer
        Public Property fadeTime As Integer
        Public Property excludeOFF As Boolean
        Public Property index As Integer
    End Class

    Public Class Mode
        Public Property name As String
        Public Property state As String
        Public Property cycle As Boolean
    End Class

    Public Class Scene
        Public Property name As String
        Public Property sceneID As Integer
        Public Property siteSceneID As Integer
        Public Property revision As Integer
        Public Property icon As Integer
        Public Property color As Integer
        Public Property position As Integer
        Public Property type As Integer
        Public Property repeat As Boolean
        Public Property hidden As Boolean
        Public Property units() As Unit1
        Public Property steps() As _Step
        Public Property conditions() As Object
        Public Property sensors() As Object
        Public Property mode As Integer
        Public Property circadianProfile As Integer
        Public Property stayOn As Boolean
    End Class

    Public Class Unit1
        Public Property unit As Integer
        Public Property state As String
    End Class

    Public Class _Step
        Public Property scene As Integer
        Public Property level As Single
        Public Property duration As Integer
    End Class

    Public Class _Event
        Public Property enabled As Boolean
        Public Property overridePresence As Boolean
        Public Property id As Integer
        Public Property siteid As Integer
        Public Property type As Integer
        Public Property revision As Integer
        Public Property startTime As Starttime
        Public Property endTime As Endtime
        Public Property duration As Integer
        Public Property fadeTime As Integer
        Public Property scenes() As Integer
        Public Property targets() As Target
    End Class

    Public Class Starttime
        Public Property dateType As Integer
        Public Property timeType As Integer
        Public Property weekdays As Integer
        Public Property year As Integer
        Public Property month As Integer
        Public Property day As Integer
        Public Property hour As Integer
        Public Property minute As Integer
        Public Property offset As Integer
    End Class

    Public Class Endtime
        Public Property dateType As Integer
        Public Property timeType As Integer
        Public Property weekdays As Integer
        Public Property year As Integer
        Public Property month As Integer
        Public Property day As Integer
        Public Property hour As Integer
        Public Property minute As Integer
        Public Property offset As Integer
    End Class

    Public Class Target
        Public Property scene As Integer
        Public Property level As Single
        Public Property duration As Integer
    End Class

    Public Class Circadianprofile
        Public Property id As Integer
        Public Property revision As Integer
        Public Property name As String
        Public Property graph As Graph
    End Class

    Public Class Graph
        Public Property type As Integer
        Public Property points() As Point
    End Class

    Public Class Point
        Public Property x As Single
        Public Property y As Single
    End Class






    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim fileReader As String
        fileReader = My.Computer.FileSystem.ReadAllText("C:\Json.txt")


        Resp_API.Text = fileReader



        Dim jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Unit)(fileReader)

        TextBox1.Text = jsonObj.name






    End Sub



End Class

#realJSOP

Вы должны опубликовать json, который вы пытаетесь десериализовать. Все, что мы можем сделать в этот момент, - это сказать: "Да! по-моему, все в порядке."

F-ES Sitecore

Вместо того чтобы пробовать все это сразу, может быть проще разбить его и получить небольшие разделы json десериализованными, и как только у вас есть небольшой бит работы, двигайтесь дальше, чтобы заставить работать другие биты. Если есть json, который не соответствует вашим классам, он просто игнорируется, вам не нужно точное совпадение, так что это позволит вам немного расширять ваши классы, решая небольшие проблемы по мере продвижения, и вы в конечном итоге создадите весь файл.

Кроме того, существуют онлайновые инструменты, в которые вы можете вставить свой json, и они будут генерировать структуры классов для вас.

Member 9992334

Извиняюсь, извиняюсь я не так с JSON...
Это небольшой раздел:
{"units":[{"deviceID":14,"address":"c29419a7442d","cpu":2,"name":"Scale campo","type":526,"appearance":0,"hueID":0,"groupID":0,"position":3,"revision":1,"configRevision":2,"firmware":6656,"modes":[{"name":"unit_mode1","state":"fc03","cycle":true},{"name":"unit_mode2","state":"0000","cycle":false},{"name":"unit_mode3","state":"0000","cycle":false},{"name":"unit_mode4","state":"0000","cycle":false}],"smartSwitch":{"type":0,"id":0,"scenes":[],"scenes2":[],"group":0,"unit":0,"lingerTime":120,"fadeTime":10,"excludeOFF":false,"index":0},"pushButtonToggleDisabled":false,"presenceSensor":{"type":5,"id":0,"scenes":[],"scenes2":[],"group":0,"unit":0,"lingerTime":120,"fadeTime":10,"excludeOFF":false,"index":0},"linkedSensor":0,"gain":100,"startupMode":1,"minOnLevel":0,"minLevel":0,"maxLevel":1,"parameters":[],"sequenceCounter":0,"behaviour":0,"timeout":0,"labels":{},"details":{},"actionConfig":0,"actions":[]},{"deviceID":15,"address":"b12897c544fa","cpu":2,"name":"Scale ingresso","type":526,"appearance":0,"hueID":0,"groupID":0,"position":3,"revision":1,"configRevision":3,"firmware":6656,"modes":[{"name":"unit_mode1","state":"0000","cycle":true},{"name":"unit_mode2","state":"0000","cycle":false},{"name":"unit_mode3","state":"0000","cycle":false},{"name":"unit_mode4","state":"0000","cycle":false}],"smartSwitch":{"type":0,"id":0,"scenes":[],"scenes2":[],"group":0,"unit":0,"lingerTime":120,"fadeTime":10,"excludeOFF":false,"index":0},"pushButtonToggleDisabled":false,"presenceSensor":{"type":5,"id":0,"scenes":[],"scenes2":[],"group":0,"unit":0,"lingerTime":120,"fadeTime":10,"excludeOFF":false,"index":0},"linkedSensor":0,"gain":100,"startupMode":1,"minOnLevel":0,"minLevel":0,"maxLevel":1,"parameters":[],"sequenceCounter":0,"behaviour":0,"timeout":0,"labels":{},"details":{},"actionConfig":0,"actions":[]}]}

Member 9992334

Наконец я понял, что проблемы были в классах, которые не были правильно сгенерированы из-за пустых массивов.
В любом случае, большое спасибо за вашу помощь.

Система Импорта
Система Импорта.Динамический
Система Импорта.Текст
Система Импорта.ИО
Система Импорта.Нет.Протокол HTTP
Система Импорта.Нарезание резьбы.Задачи
Импортирует RestSharp.Удостоверения
Импорт Web_request
Импорт Newtonsoft.В JSON
Импорт Newtonsoft.В формате JSON.В LINQ
Импорт RestSharp




Общественного Класса Form1
Частная суб обработчика button1_click(отправителя как объект, а равно EventArgs) обрабатывает кнопки button1.Щелчок
Dim fileReader в виде строки
fileReader = My.Computer.Файловая Система.ReadAllText("C:\Json6.txt")

Resp_API.Text = fileReader

Dim jsonObj = JsonConvert.DeserializeObject(Of Rootobject)(fileReader)

Дим корень = jsonObj.единиц.Пункт 9)
Текстовое поле textbox1.Текст = корень.название


Конец Подводной Лодки


End Класса



Публичный Класс RootObject
Единицы публичной собственности в виде списка(единицы измерения)
End Класса

Единица Измерения Общественного Класса
Идентификатора устройства общенародная собственность как целое
Адрес публичной собственности в виде строки
Процессор общественная собственность как целое
Имя публичного свойства в виде строки
Тип публичного свойства как целое число
Внешний вид публичной собственности в виде целого числа
Публичная собственность hueID как целое число
Общественная собственность группы как целого
Позиция публичной собственности как целое число
Ревизия публичной собственности в виде целого числа
Публичное свойство configRevision как целое число
Прошивка публичной собственности как целое число
Режимы общественная собственность как список(в режим)
Описание государственного имущества в качестве устройства
Общественная собственность pushButtonToggleDisabled как логическое
Датчик присутствия общественной собственности как устройство
LinkedSensor общественная собственность как целое
Прирост публичной собственности в виде целого числа
StartupMode общественная собственность как целое
Публичное свойство minOnLevel как целое число
Публичное свойство minLevel как целое число
Публичное свойство maxLevel как целое число
Параметры публичного свойства в виде списка(строки)
SequenceCounter общественная собственность как целое
Поведение публичной собственности как целое число
Тайм-аут публичного свойства в виде целого числа
Ярлыки общественной собственности как ярлыки
Детали общественной собственности как детали
ActionConfig общественная собственность как целое
Действия публичного свойства в виде списка(строки)
End Класса

Устройства Открытый Класс
Тип публичного свойства как целое число
Идентификатор публичного свойства в виде целого числа
Сцены публичного свойства в виде списка(строки)
Scenes2 общественная собственность как список(строки)
Группа публичных свойств как целое число
Единица публичной собственности как целое число
Публичное свойство lingerTime как целое число
Публичное свойство fadeTime как целое число
ExcludeOFF общественная собственность как логическое
Индекс публичной собственности в виде целого числа
End Класса



Метки Публичных Классов
End Класса

Сведения О Публичном Классе
End Класса

Режим Публичного Класса
Имя публичного свойства в виде строки
Состояние публичной собственности как строка
Цикл публичной собственности как логический
End Класса

0 Ответов