JSON还原为结构体
1)JSON字符串还原为结构体; 2)访问结构体的字段值; 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 + ' "A cronym": "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)); 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]); // 咏南中间件 end; cronym": "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)); 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]); // 咏南中间件 end;
用户评论