结构体序列为JSON

结构体序列为JSON

本例运行效果图:

uses
SynCommons;

const /// JSON字符串
JSON1 =
'{' + #13#10 + '"glossary": {' + #13#10 + '"title": "中国",' + #13#10
+ ' "GlossDiv": {' + #13#10
+ '"title": "湖南省",' + #13#10
+ ' "GlossList": {' + #13#10
+ '"GlossEntry": {' + #13#10
+ '"ID": "湘乡市",' + #13#10
+ ' "SortAs": "SGML",' + #13#10
+ ' "GlossTerm": "Standard Generalized Markup Language",' + #13#10
+ ' "Acronym": "SGML",' + #13#10
+ ' "Abbrev": "ISO 8879:1986",' + #13#10
+ ' "GlossDef": {' + #13#10
+ '"para": "A meta-markup language, used to create markup languages such as DocBook.",' + #13#10
+ ' "GlossSeeAlso": ["咏南中间件", "XML"]' + #13#10
+ '},' + #13#10
+ ' "GlossSee": "markup"' + #13#10 + '}'
+ #13#10 + '}' + #13#10
+ '}' + #13#10
+ '}' + #13#10
+ '}';

type // 记录
TGlossary = record
glossary: record
title: string;
GlossDiv: record
title: string;
GlossList: record
GlossEntry: record
ID, SortAs, GlossTerm, Acronym, Abbrev: string;
GlossDef: record
para: string;
GlossSeeAlso: array of string;
end;
GlossSee: string;
end;
end;
end;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
gloss: TGlossary;
json: RawUTF8;
begin
json := JSON1;
RecordLoadJSON(gloss, @json[1], TypeInfo(TGlossary)); // JSON还原为结构体
Memo1.Clear;
Memo1.Lines.Add(gloss.glossary.title); // 中国
Memo1.Lines.Add(gloss.glossary.GlossDiv.title); // 湖南省
Memo1.Lines.Add(gloss.glossary.GlossDiv.GlossList.GlossEntry.ID); // 湘乡市
Memo1.Lines.Add(gloss.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso[0]); // 咏南中间件
json := '';
json := RecordSaveJSON(gloss, TypeInfo(TGlossary)); // 结构体序列为JSON
Memo1.Text := json;
end;

 

posted @ 2018-04-11 09:46  delphi中间件  阅读(616)  评论(0编辑  收藏  举报