Invalid class typecast ошибка

I am trying to parse a JSON result from the Twitter API using Delphi XE7. I am getting an «Invalid class typecast» error, but I check the JSON with an online verifier and it is OK.

Here is the JSON result:

[
  {
    "trends":
    [
      {
        "name":"#OneDirectionIsOverParty",
        "url":"http://twitter.com/search?q=%23OneDirectionIsOverParty",
        "promoted_content":null,
        "query":"%23OneDirectionIsOverParty",
        "tweet_volume":410022
      },
      {
        "name":"#TheDarkKnight",
        "url":"http://twitter.com/search?q=%23TheDarkKnight",
        "promoted_content":null,
        "query":"%23TheDarkKnight",
        "tweet_volume":null
      },
      {
        "name":"#QuintaComOClubeSdv",
        "url":"http://twitter.com/search?q=%23QuintaComOClubeSdv",
        "promoted_content":null,
        "query":"%23QuintaComOClubeSdv",
        "tweet_volume":23756
      }
    ],
    "as_of":"2016-07-21T20:14:13Z",
    "created_at":"2016-07-21T20:08:31Z",
    "locations":
    [
      {
        "name":"Worldwide",
        "woeid":1
      }
    ]
  }
]

This is my parsing function:

procedure ParseJSON(const JSON: string);
var
 JSONObject: TJSONObject;
 MessageText: TJSONArray;
 NodeDetails: TJSONObject;
 MsgDetail: TJSONString;
 I: Integer;
 Item: TListItem;
begin
 JSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(JSON), 0) as TJSONObject;
 MessageText := JSONObject.Get('trends').JSONValue as TJSONArray;

for I := 0 to TJSONArray(MessageText).Size - 1 do
begin
  Item := Form1.ListView1.Items.Add;
  NodeDetails := MessageText.Get(I) as TJSONObject;
  MsgDetail := NodeDetails.Get('query').JSONValue as TJSONString;
  Item.Caption := MsgDetail.Value;
end;

Actually, this function works with other JSON results from the Twitter API. It is not working on this one result only.

Sabes

0 / 0 / 1

Регистрация: 05.02.2016

Сообщений: 33

1

24.06.2018, 00:26. Показов 13292. Ответов 12

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Нужно чтобы при нажатии на кнопку создавался новый компонент Image, который находится правее предыдущего. И все работает без ошибок, но только если на форме отсутствует Label. Как только я добавлю Label в любое место, при создании компонента вылетает ошибка «invalid class typecast». При этом если на форме будет StaticText1, который подобен Label ошибка вылетать не будет.
Код:

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
procedure TForm3.Button1Click(Sender: TObject);
var img: TImage;
     i,imageCount:integer;
begin
  imageCount:=-1;
  for i:=0 to ControlCount-1 do
    Begin
      if (Controls[i] is TImage) then
        inc(imageCount);
    End;
if imageCount=-1 then
  Begin
    img:=TImage.Create(Form3);
    img.Name:='Image1';
    img.Parent:=Form3;
    img.Left:=10;
    img.Top:=10;
    img.Width:=155;
    img.Height:=130;
    img.Picture.LoadFromFile(ExtractFilepath(Application.ExeName)+'Shablons111.jpg');
  End
else
  Begin
    img:=TImage.Create(Form3);
    img.Name:='Image'+IntToStr(imageCount+2);
    img.Parent:=Form3;
    img.Left:=(Controls[imageCount] as TImage).Left+(Controls[imageCount] as TImage).Width+10;
    img.Top:=10;
    img.Width:=155;
    img.Height:=130;
    img.Picture.LoadFromFile(ExtractFilepath(Application.ExeName)+'Shablons111.jpg');
  End;
end;

Ошибка так же вылетает на компонент DbText, и на все IW-компоненты.
Понятия не имею в чем проблема.



0



northener

пофигист широкого профиля

4658 / 3093 / 854

Регистрация: 15.07.2013

Сообщений: 17,841

24.06.2018, 01:55

2

Цитата
Сообщение от Sabes
Посмотреть сообщение

вылетает ошибка «invalid class typecast»

Это сообщение выдаётся при использовании оператора as и только при его использовании!
Ваш алгоритм

Delphi
1
img.Left:=(Controls[imageCount] as TImage).Left+(Controls[imageCount] as TImage).Width+10;

не годится. Заведите свой список именно картинок.

Цитата
Сообщение от Sabes
Посмотреть сообщение

При этом если на форме будет StaticText1, который подобен Label ошибка вылетать не будет.
Код:

TStaticText не является наследником TControl и естественно в список Controls не включается.



1



0 / 0 / 1

Регистрация: 05.02.2016

Сообщений: 33

24.06.2018, 02:01

 [ТС]

3

northener, Спасибо, теперь я понял. Я смогу избежать ошибок если будут использовать Components, вместо Controls?



0



пофигист широкого профиля

4658 / 3093 / 854

Регистрация: 15.07.2013

Сообщений: 17,841

24.06.2018, 02:10

4

Нет, не сможете. Список Components ещё шире, чем список Controls. Вам нужно сделать свой список/массив, который будет хранить указатели только на ваши картинки.



0



0 / 0 / 1

Регистрация: 05.02.2016

Сообщений: 33

24.06.2018, 02:36

 [ТС]

5

northener, Не подскажите как сделать такой список/массив? Или литературу где это описано, потому что я к сожалению не знаю как это сделать.



0



пофигист широкого профиля

4658 / 3093 / 854

Регистрация: 15.07.2013

Сообщений: 17,841

24.06.2018, 02:50

6

Если до вечера воскресенья никто вам не даст пример кода, я его напишу. А литературы где это описано нет.
Тут собственно описывать нечего.



0



0 / 0 / 1

Регистрация: 05.02.2016

Сообщений: 33

24.06.2018, 03:12

 [ТС]

7

northener, Буду очень признателен за пример кода.



0



5089 / 4103 / 1026

Регистрация: 29.08.2013

Сообщений: 26,008

Записей в блоге: 3

24.06.2018, 08:26

8

Массив вы умеете добавлять?
Тут точно так же, только массив из TImage



0



krapotkin

5537 / 4322 / 1383

Регистрация: 14.04.2014

Сообщений: 19,381

Записей в блоге: 19

24.06.2018, 09:31

9

Delphi 2010+

Delphi
1
2
3
4
TForm1=class
...
ImgList : TObjectList<TImage>;
end;

OnCreate

Delphi
1
ImgList:=TObjectList<TImage>.Create(true);

OnDestroy

Delphi
1
FreeAndNil(ImgList);

Добавление элемента

Delphi
1
2
Img:=TImage.Create(Self);
ImgList.Add(Img);



0



0 / 0 / 1

Регистрация: 05.02.2016

Сообщений: 33

25.06.2018, 03:47

 [ТС]

10

krapotkin, Работаю в Delphi 7 и вылетает ошибка на то что программа не знает TObjectList. Как я понял это потому что в Delphi 7 отсутствует Generics.Collections. Есть ли другой способ? Или придется скачивать новую версию?



0



Модератор

8487 / 5647 / 2290

Регистрация: 21.01.2014

Сообщений: 24,228

Записей в блоге: 3

25.06.2018, 04:33

11

Цитата
Сообщение от Sabes
Посмотреть сообщение

Есть ли другой способ?

Есть. И Вам про него уже сказали — динамический массив объектов типа TImage

Цитата
Сообщение от Sabes
Посмотреть сообщение

придется скачивать новую версию?

Как бы давно пора…



0



krapotkin

5537 / 4322 / 1383

Регистрация: 14.04.2014

Сообщений: 19,381

Записей в блоге: 19

25.06.2018, 07:41

12

Цитата
Сообщение от Sabes
Посмотреть сообщение

Работаю в Delphi 7

еще раз внимательно прочел ваш вопрос. пытался найти что-то про Delphi 7
не нашел)
зато нашел

Цитата
Сообщение от krapotkin
Посмотреть сообщение

Delphi 2010+

для D7

Delphi
1
2
3
4
5
6
7
8
9
10
11
TForm1=class
...
ImgList : TObjectList;
end;
...
ImgList:=TObjectList.Create(true);
...
Img:=TImage.Create(Self);
ImgList.Add(Img);
...
Img := TImage(ImgList[i]);



0



Модератор

8487 / 5647 / 2290

Регистрация: 21.01.2014

Сообщений: 24,228

Записей в блоге: 3

25.06.2018, 08:16

13

Для семерки еще надо в uses добавить Contnrs



0



Seth

Newbie
Newbie
Posts: 92
Joined: Tue Aug 17, 2004 4:00 am

[Invalid class typecast] Error

Hi,

I have a question.
I am using TeeChart Pro v7 ActiveX.
But Some series have error.

1. Choose one of series that Extended_Polar ,Extended_Radar,Extended_Polar Bar,Extended_Smith or Other_Wind Rose.
2. Add the series and set Random Data.
3. After that, Export [TChart1.Export.asNative.SaveToFile App.Path & «teefile.tee», True] function.
4. And Import [TChart1.Import.LoadFromFile App.Path + «teefile.tee»].
5. Then, there is an [Invalid class typecast] message box. So, I have to quit APP.

I tested your Sample program [C:Program FilesSteema SoftwareTeeChart Pro v7 ActiveX Unicode VersionexamplesUnicodeTestUnicodeProject.exe].
But It had same error.

I attached an error image.

Confirm, and answer me please.

Attachments
teechart_polarerror.JPG
teechart_polarerror.JPG (155.22 KiB) Viewed 22571 times


Narcís

Site Admin
Site Admin
Posts: 14730
Joined: Mon Jun 09, 2003 4:00 am
Location: Banyoles, Catalonia
Contact:

Re: [Invalid class typecast] Error

Post

by Narcís » Tue Dec 07, 2010 11:48 am

Hi Seth,

I’m not able to reproduce the issue here using latest TeeChart 2010 and v8 ActiveX releases with this code:

Code: Select all

Private Sub Command1_Click()
    TChart1.Export.asNative.SaveToFile "C:tempAX.tee", True
End Sub

Private Sub Command2_Click()
    TChart1.ClearChart
    TChart1.Import.LoadFromFile "C:tempAX.tee"
End Sub

Private Sub Form_Load()
    TChart1.AddSeries scPolar
    TChart1.Series(0).FillSampleValues 10
End Sub

Does this work fine for you? Which is the exact TeeChart version you use? Can you please try if using latest evaluation version solves the problem at your end?

Thanks in advance.


Seth

Newbie
Newbie
Posts: 92
Joined: Tue Aug 17, 2004 4:00 am

Re: [Invalid class typecast] Error

Post

by Seth » Wed Dec 08, 2010 5:13 am

I used TeeChart Pro V7.0.1.4 ActiveX and VC++ 6.0.

Code: Select all

BOOL CTestchart2Dlg::OnInitDialog()
{
           CDialog::OnInitDialog();

           m_chart.ClearChart();
     m_chart.AddSeries(12); //scPolar 
   
           m_chart.Series(0).FillSampleValues(10);
           return TRUE;
} 

When This OnInitDialog() executes, [Invalid Class Typecast] message occures repeatly, so I have to quit ActiveX.
Without Import and Export, it occures when add one of the series among Polar(12) ,Radar(20),Polar Bar(45),Smith(34),Wind Rose(22) In AddSeries

Please Check again.


Yeray

Site Admin
Site Admin
Posts: 9350
Joined: Tue Dec 05, 2006 12:00 am
Location: Girona, Catalonia
Contact:

Re: [Invalid class typecast] Error

Post

by Yeray » Mon Dec 13, 2010 2:00 pm

Hi Seth,

It’s strange, the attached VC++6 project seems to reproduce the problem in a machine and not in another one, both running TeeChart AX v7.0.1.4.

However, it seems to work fine with v8 and v2010 in the machine where the problem was reproduced.
So could you please try the v2010 evaluation to see if the problem is reproducible for you with it?
http://www.steema.com/evaluation/ax
Thanks in advance


Seth

Newbie
Newbie
Posts: 92
Joined: Tue Aug 17, 2004 4:00 am

Re: [Invalid class typecast] Error

Post

by Seth » Fri Dec 17, 2010 2:27 am

Hi!

There was a same problem with your Sample Project in TeeChart Pro V7.
But in TeeChart Pro V2010 evaluation, there was no problem.

So, We want to fix it. (TeeChart Ver7)
Because we have to use Series that are occured an error for our customer.

Would you fix the problem in TeeChart ver.7?

I hope so.


Yeray

Site Admin
Site Admin
Posts: 9350
Joined: Tue Dec 05, 2006 12:00 am
Location: Girona, Catalonia
Contact:

Re: [Invalid class typecast] Error

Post

by Yeray » Fri Dec 17, 2010 11:44 am

Hi Seth,

Since TeeChart AX v8 was released more than 3 years ago, and TeeChart AX v2010 about two months ago, as you’ll understand, I’m afraid we don’t have plans to publish another TeeChart AX v7 maintenance release.
If you want to upgrade to TeeChart v2010, please contact the sales department at: sales at steema dot com


Seth

Newbie
Newbie
Posts: 92
Joined: Tue Aug 17, 2004 4:00 am

Re: [Invalid class typecast] Error

Post

by Seth » Mon Dec 20, 2010 8:23 am

Hi,

First, Thank for your answer.
But We bought TeeChart ver.7 included Extended_Polar,Extended_Radar,Extended_Polar Bar,Extended_Smith or Other_Wind Rose series.
And It’s Menual said that functions are provided in Teechart ver.7.
in addition, We have a problem updating Teechart Ver.7 to 2010.

I Understand that you are too hard to fix Teechart ver7,
This problem is production faulty. so, I ask for you to fix it.

I’ll waiting for your positive answer.


Yeray

Site Admin
Site Admin
Posts: 9350
Joined: Tue Dec 05, 2006 12:00 am
Location: Girona, Catalonia
Contact:

Re: [Invalid class typecast] Error

Post

by Yeray » Thu Dec 23, 2010 12:33 pm

Hi Seth,

The problem seems not to be reproducible here with TeeChart ActiveX v7.0.1.2 in the same machine where we could reproduce the problem with v7.0.1.4.
I’ve sent a mail with the v7.0.1.2 ocx to the mail account you have registered in these forums.

I hope it helps.


Seth

Newbie
Newbie
Posts: 92
Joined: Tue Aug 17, 2004 4:00 am

Re: [Invalid class typecast] Error

Post

by Seth » Fri Dec 24, 2010 2:23 am

Hello.

I appreciated your answer.

I checked on TeeChart ActiveX v7.0.1.2. There was not problem with Add Series.
But it is difficult that distribute TeeChart ActiveX v.7.0.1.2. Because many of our customers had TeeChart ver.7.0.1.4 that was distributed by us.

And If we use v.7.0.1.2, some of Add Series problems are solved.
However There is no guarantee that Any problem may not be occurred.

Actually, This Problem is some of a Degradation upgrading from ver.7.0.1.2 to ver.7.0.1.4.
I understand that you have a trouble, but I ask you to reconsider to fix it.

I’ll waiting your answer.


Marc

Site Admin
Site Admin
Posts: 1126
Joined: Thu Oct 16, 2003 4:00 am
Location: Girona
Contact:

Re: [Invalid class typecast] Error

Post

by Marc » Mon Dec 27, 2010 12:52 pm

Hello,

We’ll prepare a v7 update to resolve this issue. Hopefully we can have that ready within a week or two (we are looking at another issue we’d like to include in this update too).

Regards,
Marc Meumann

Steema Support



Seth

Newbie
Newbie
Posts: 92
Joined: Tue Aug 17, 2004 4:00 am

Re: [Invalid class typecast] Error

Post

by Seth » Tue Jan 25, 2011 5:16 am

Thank you for your kindness.

I checked that execute very well.
But I need Multi-Language version, too.
So, I ask for your favor, again.


Marc

Site Admin
Site Admin
Posts: 1126
Joined: Thu Oct 16, 2003 4:00 am
Location: Girona
Contact:

Re: [Invalid class typecast] Error

Post

by Marc » Wed Jan 26, 2011 4:09 pm

Hello,

There is now a new multi-language version 7 on the customer download page.

Regards,
Marc


Seth

Newbie
Newbie
Posts: 92
Joined: Tue Aug 17, 2004 4:00 am

Re: [Invalid class typecast] Error

Post

by Seth » Fri Jan 28, 2011 7:23 am

Hello,

First, Thank you for new module!

I’m sorry but I need TeeChart7.ocx for Unicode, too.
That is not multi-language.

So, I ask for your kindness, again please


Yeray

Site Admin
Site Admin
Posts: 9350
Joined: Tue Dec 05, 2006 12:00 am
Location: Girona, Catalonia
Contact:

Re: [Invalid class typecast] Error

Post

by Yeray » Mon Jan 31, 2011 2:34 pm

Hi seth,

The version published on 26th January is Unicode, isn’t it?
TeeChartAX7UpdateMultiLangUnicode.exe


Добрый день. Система из С-2000 и несколько Сигнал10П. , БИ. При нажатии в PProg, на пиктограмму считывания ключа, выдает «Invalid class typecast». И после этого, программа перестает записывать конфигурацию. Вручную номера чипов добавляються и работают. Программируем в 7-ке.

2 года 6 месяцев назад

avatar

Руденко Андрей Валерьевича

3

#ссылка

2 ответа

«Семёра»- самая лучшая вещь для программирования. Специально её не «переустанавливаю»
Никогда такого не было.
Как вариант…
Либо ключи не те…Либо «ключи-клоны».
Можете другой версией PProg попробовать. Возможно,что результат будет другой.
Обойдётся и без «инвалидов».

2 года 6 месяцев назад

avatar

Каргапольцев Артур Николаевич

10906

#ссылка

Переустановил PProg, не помогло (антивир ругался, при установке, тотал 360+). Поставил старую версию 3.03 билд 1. Она заработала.

2 года 6 месяцев назад

avatar

Руденко Андрей Валерьевича

3

#ссылка

Добавить ответ

Для добавления сообщений на форуме вам необходимо зарегистрироваться и указать мобильный телефон в своем профиле (зачем?)

ЗАДАН

2 года 6 месяцев назад

По каждому вопросу/ответу можно добавлять комментарии. Комментарии предназначены для уточнения вопроса/ответа.

@esseredigitale @spinettaro

Did you use TStyleEdit, TCheckBox, TActiveStyleTextObject as the Subscriber Object, thus having the Form class as their Parent?

we are making a demo without db and other components …
For now I can tell you that the project is made with a DataModule with a component MQTT client that receives messages from a server and for each message we do a globalevent post.

procedure TDMMain.TMSMQTTClient1PublishReceived(ASender: TObject; APacketID: Word; ATopic: string; APayload: TArray<System.Byte>);
var
  _pl: string;
  _devicename, _topic : string;
  LEvent: IMQTTReceiveEvent;
begin
  _pl := TEncoding.UTF8.GetString(APayload);
  _devicename := copy(ATopic,0,pos('/',ATopic) - 1);
  _topic := Copy(ATopic,pos('/',ATopic),length(ATopic)-length(_devicename));
  if _topic = STATUS then
  begin
    LEvent := GetMQTTReceiveEvent;
    LEvent.SN := _devicename;
    LEvent.Payload := _pl;
    ToCodeSite('LEvent',LEvent.SN + ' ' + LEvent.Payload);
    try
      GlobalEventBus.Post(LEvent);
    except
      on e : exception do
      begin
        ToCodeSite('GlobalEventBus.Post(LEvent) except: ', e.Message);
      end;
    end;
  end;
end;

Subscriber are in many frames on a TGridLayout on the main form.

[Subscribe(TThreadMode.Main)]
procedure NewUpdateStatus(AEvent: IMQTTReceiveEvent);
[...]
procedure TfrOzonum.NewUpdateStatus(AEvent: IMQTTReceiveEvent);
var
  _payload, _temp, _Umid, _ozo: string;
begin
  try
    if AEvent.SN = SN then
    begin
      Mostra;
      DMMain.ToCodeSite('Update Status From Ozonum', SN + ': Sto scompattando il pacchetto');
      _payload := AEvent.Payload;
      _temp := copy(_payload,2,5);
      _Umid := copy(_payload,7,5);
      _ozo  := copy(_payload,12,5);
      Temperatura  := StrToInt(_temp);
      Umidita      := StrToInt(_Umid);
      Ozono        := StrToInt(_ozo);
      Ozonizzatore := StrToInt(_payload[17]);
      Ventola      := StrToInt(_payload[18]);
    end;
  Except
    on e : exception do
    begin
      DMMain.ToCodeSite('New Update Status from Ozonum except: ', e.Message);
    end;
  end;
end;

What do you mean when write «Subscriber Object»?

If so, then that is THE PROBLEM.

If you look into System.Rtti for the source of the Rtti Invoke code (as in the Figure) — you will see that an EInvalidCast exception will be thrown, if the Subscriber Object is NOT of a derived type of its PARENT.

This explain why TForm, TFrame, TDateModule works, while TStyleEdit, TCheckBox, TActiveStyleTextObject NOT.

So basically, the conclusion is that: we cannot have child components dropped to a Form as the Subscribe Object., at all.

2020-12-02_18-47-15

TStyleEdit and TActiveStyleTextObject are used in the TStylebook of the main form.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Invalid authentication token ark ошибка
  • Invalid attempt already authenticated ark ошибка
  • Invalid assignment ansys ошибка
  • Invalid argument supplied for foreach in ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии