Serializing a TObjectList (Bcl.Json)

Hi.
I need to serialize a object in order to generate a JSON like this:
..
{
"cobrancas": [
{
"vencimento": "12/30/2019",
"valor": "50.75",
"juros": "0",

    }
]

}
``
I have a object list TCobrancas, and I used TJSon.Serialize(Cobrancas)
But, my JSon become this:

[{"vencimento":"01/02/2021","valor":"1180.28","juros":"10"}]

How can I fixed this?

Thanks.

Hi, one way is to make your TCobrancas like this:

TListaCobrancas = class
private
  FCobrancas: TList<TCobranca>;
public
  {..}
  property Cobrancas: TList<TCobranca> read FCobrancas;
end;

Than

var
  LLista: TListaCobrancas;
begin
  LLista := TListaCobrancas.Create;
  {...LLista.Cobrancas.Add...}
  JsonText := TJson.Serialize(LLista);

Regards,

1 Like

But, it's exactly what I did.
Could you see the difference between the JSON I wanted and the what was generate?
Thanks.

Well, I guess the result you are getting is from serializing the object list.

If you serialize the object containing the object list (as a Cobrancas property) than the result will be exactly what you want.

Regards,

You used TList. I used TObjectList. There are some difference?
Look:
[{"vencimento":"01/02/2021","valor":"1180.28","juros":"10"}]
I´d like this ""cobrancas": [ "in begin of sentence.
But, I wiil tray again.
Thanks again!

You used TList. I used TObjectList. There are some difference?

I think makes no difference.

Look closely my example. It's not serializing a TList (or a TObjectList)
It is serializing an Object that keeps reference to a TList through a property named Cobrancas

Are you doing the same? Can you share part of you code?

Regards,

Yes, I looked closely yor example before you said here, hahaha.
So I saw.
I got confused with the properties.
I was wrong
I fixed and works fine.
Learned one more.
Thank you.

2 Likes