如何在Delphi中打印JSON? [英] How do I pretty-print JSON in Delphi?

查看:175
本文介绍了如何在Delphi中打印JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可以输入JSON字符串的函数,并使用换行符和缩进(tab)进行格式化。

I am looking for a function that will take a string of JSON as input and format it with line breaks and indentations (tabs).

示例:
我有输入行:

Example: I have input line:

{"menu": {"header": "JSON viewer", "items": [{"id": "Delphi"},{"id": "Pascal", "label": "Nice tree format"}, null]}}

想要以文本形式获得可读取的结果:

And want to get a readable result as text:

{
   "menu":{
      "header":"JSON viewer",
      "items":[
       {
         "id":"Delphi"
       },
       {
         "id":"Pascal",
         "label":"Nice tree format"
       },
       null
      ]
   }
}

我发现很多PHP和C#的例子,但不是Delphi。
有人可以帮助这样的功能吗?

I found a lot of examples for PHP and C#, but not for Delphi. Could someone help with such a function?

更新 - 使用SuperObject解决方案

function FormatJson (InString: WideString): string; // Input string is "InString"
var
  Json : ISuperObject;
begin
  Json := TSuperObject.ParseString(PWideChar(InString), True);
  Result := Json.AsJson(true, false); //Here comes your result: pretty-print JSON
end;


推荐答案

使用超对象库,确保使用<一个href =http://stackoverflow.com/questions/18445280/superobject-cannot-handle-null-string/18462331#18462331>存储库文件的最新版本,而不是1.2.4 ZIP 。

Use the superobject library, make sure that you use the latest version from the repository file, not the 1.2.4 ZIP.

然后,您可以使用格式化TSuperObject对象.AsJSON(true)(true 。

Then you can format your TSuperObject object with .AsJSON(true) (the 'true' does the trick).

[请注意,您无法控制显示JSON字段的顺序]

[ Note that you have no control over the order in which the JSON fields are displayed ]

[和从字符串创建对象: var lJSON:ISuperObject; lJSON:= SO(string); ]

[ And to create your object from the string: var lJSON : ISuperObject; lJSON := SO(string); ]

这篇关于如何在Delphi中打印JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆