JSONValue缩进字符串 [英] JSONValue to Indented String
问题描述
在Delphi XE2中,我需要创建一个接收JSONValue
并返回缩进的String
的函数,就像 JSONLint .这个JSONValue可以是任何类型的JSON,可以是数组,对象甚至是字符串,因此我必须确保使用此函数覆盖所有类型.我不知道从哪里开始.
In Delphi XE2, I need to make a function that receives a JSONValue
and returns an indented String
, much like JSONLint. This JSONValue could be any type of JSON, could be an array, an object, even just a string, so I have to make sure to cover all types with this function. I have no idea where to start.
推荐答案
您将必须递归地进行操作.像这样:
You'll have to do it recursively. Something like this:
const INDENT_SIZE = 2;
procedure PrettyPrintJSON(value: TJSONValue; output: TStrings; indent: integer = 0); forward;
procedure PrettyPrintPair(value: TJSONPair; output: TStrings; last: boolean; indent: integer);
const TEMPLATE = '%s : %s';
var
line: string;
newList: TStringList;
begin
newList := TStringList.Create;
try
PrettyPrintJSON(value.JsonValue, newList, indent);
line := format(TEMPLATE, [value.JsonString.ToString, Trim(newList.Text)]);
finally
newList.Free;
end;
line := StringOfChar(' ', indent * INDENT_SIZE) + line;
if not last then
line := line + ','
output.add(line);
end;
procedure PrettyPrintJSON(value: TJSONValue; output: TStrings; indent: integer);
var
i: integer;
begin
if value is TJSONObject then
begin
output.add(StringOfChar(' ', indent * INDENT_SIZE) + '{');
for i := 0 to TJSONObject(value).size - 1 do
PrettyPrintPair(TJSONObject(value).Get(i), output, i = TJSONObject(value).size - 1, indent + 1);
output.add(StringOfChar(' ', indent * INDENT_SIZE) + '}');
end
else if value is TJSONArray then
//left as an exercise to the reader
else output.add(StringOfChar(' ', indent * INDENT_SIZE) + value.ToString);
end;
这涵盖了基本原理.警告:我把它写在头顶上.它可能不正确甚至无法编译,但这是一般的想法.此外,您还必须提出自己的打印JSON数组的实现.但这应该可以帮助您入门.
This covers the basic principle. WARNING: I wrote this up off the top of my head. It may not be correct or even compile, but it's the general idea. Also, you'll have to come up with your own implementation of printing a JSON array. But this should get you started.
这篇关于JSONValue缩进字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!