JSON in Delphi with examples

As more developers look to create programs that can run on several operating systems, cross-platform application development has grown in popularity. In cross-platform development, controlling application settings is a crucial step. With some helpful components and examples, we’ll go over how to utilize JSON to store application settings in Delphi in this post.

What is JSON?

JSON (JavaScript Object Notation) is a simple data exchange format that is simple for both humans and machines to read, write, parse, and produce. Although it is built on a portion of JavaScript, it is not dependent on JavaScript to function.

JSON is frequently used in web applications to store configuration information and other settings, but it may also be utilized in desktop and mobile apps. JSON can be used in Delphi to store application settings that are simple to read and write on several platforms.

Using JSON to Store Application Settings in Delphi

You must use a JSON library or component in Delphi to use JSON to store application settings. SuperObject, DelphiJSON, and mORMot are just a few of the free and open source JSON components that are readily available for Delphi.

After selecting a JSON component, you can begin storing and retrieving application settings using it. Here is an illustration of how to use SuperObject to store and retrieve application settings:

uses

SuperObject;

procedure SaveSettings;

var

Settings: ISuperObject;

begin

Settings := TSuperObject.Create;

Settings.S[‘Username’] := ‘John’;

Settings.S[‘Password’] := ‘mypassword’;

Settings.I[‘Port’] := 8080;

Settings.B[‘RememberMe’] := True;

Settings.SaveTo(‘settings.json’);

end;

procedure LoadSettings;

var

Settings: ISuperObject;

begin

Settings := TSuperObject.Create;

Settings.LoadFromFile(‘settings.json’);

ShowMessage(Settings.S[‘Username’]);

ShowMessage(Settings.S[‘Password’]);

ShowMessage(IntToStr(Settings.I[‘Port’]));

ShowMessage(BoolToStr(Settings.B[‘RememberMe’], True));

end;

In this illustration, the application settings are stored in a brand-new TSuperObject. A username, password, port number, and a boolean flag to remember the user were then set as values for the settings. The settings are then saved to a file called settings.json.

We import the settings.json file into a new TSuperObject to retrieve the settings, and then we use the S, I, and B properties to get the settings’ values.

Free JSON Components for Delphi

To save and retrieve application settings, you can use the following free JSON components for Delphi:

A quick and efficient JSON library for Delphi called SuperObject.

DelphiJSON is a straightforward and user-friendly JSON library for Delphi.

mORMot: A robust and adaptable open source Delphi framework that supports JSON.

Example 1: Reading JSON Data from a URL

You can use Delphi’s TNetHTTPClient component to retrieve JSON data from a URL. Here’s an example of how to retrieve JSON data from the OpenWeatherMap API:

uses

System.Net.HttpClient, System.JSON;

procedure GetWeatherData;

var

Client: TNetHTTPClient;

Response: IHTTPResponse;

JSONData: TJSONObject;

begin

Client := TNetHTTPClient.Create(nil);

try

Response := Client.Get(‘https://api.openweathermap.org/data/2.5/weather?q=New%20York&appid=YOURAPPID’);

if Response.StatusCode = 200 then

begin

JSONData := TJSONObject.ParseJSONValue(Response.ContentAsString) as TJSONObject;

ShowMessage(JSONData.GetValue(‘name’).Value);

ShowMessage(JSONData.Get(‘weather’).JsonValue.ToString);

ShowMessage(JSONData.Get(‘main’).GetValue(‘temp’).Value);

end;

finally

Client.Free;

end;

end;

In this example, we use TNetHTTPClient to retrieve JSON data from the OpenWeatherMap API. We then parse the JSON data using Delphi’s built-in TJSONObject class and display some of the data in a message box.

Example 2: Writing JSON Data to a File

You can use Delphi’s TStreamWriter component to write JSON data to a file. Here’s an example of how to create a JSON file with some sample data:

uses

System.JSON, System.Classes;

procedure WriteJSONToFile;

var

Writer: TStreamWriter;

JSONData: TJSONObject;

begin

JSONData := TJSONObject.Create;

JSONData.AddPair(‘name’, ‘John’);

JSONData.AddPair(‘age’, TJSONNumber.Create(30));

JSONData.AddPair(‘isMarried’, TJSONBool.Create(True));

Writer := TStreamWriter.Create(‘sample.json’);

try

Writer.Write(JSONData.ToString);

finally

Writer.Free;

end;

end;

In this example, we create a new TJSONObject with some sample data (a name, age, and marital status). We then create a new TStreamWriter to write the JSON data to a file called sample.json.

Example 3: Executing a JSON-RPC Call

JSON-RPC is a remote procedure call (RPC) protocol encoded in JSON. You can use Delphi’s TIdHTTP component to execute a JSON-RPC call. Here’s an example of how to execute a JSON-RPC call using the Blockchain.info API:

uses

IdHTTP, IdGlobal, System.JSON;

procedure ExecuteJSONRPC;

var

IdHTTP: TIdHTTP;

JSONRequest: TJSONObject;

JSONResponse: TJSONObject;

ResponseString: string;

begin

IdHTTP := TIdHTTP.Create(nil);

try

JSONRequest := TJSONObject.Create;

JSONRequest.AddPair(‘method’, ‘blockchain.info/latestblock’);

JSONRequest.AddPair(‘params’, TJSONArray.Create);

ResponseString := IdHTTP.Post(‘https://blockchain.info/‘, JSONRequest.ToString, IndyTextEncoding_UTF8);

JSONResponse := TJSONObject.ParseJSONValue(ResponseString) as TJSONObject;

ShowMessage(JSONResponse.GetValue(‘hash’).Value);

finally

IdHTTP.Free;

end;

end;

In this example, we use TIdHTTP to execute a JSON-RPC call to the Blockchain.info API. We build a new JSON request using Delphi’s TJSONObject class and add the method and params values. We then use TIdHTTP to post the JSON request to the API and receive a response. Finally, we parse the JSON response using TJSONObject.ParseJSONValue and display some of the data in a message box.

These are just a few examples of how to read, write, and execute JSON in Delphi. There are many more use cases for JSON, including serialization, deserialization, and data storage. To work with JSON in Delphi, you can use built-in classes such as TJSONObject and TJSONValue, as well as third-party libraries like SuperObject and mORMot.

Conclusion

Managing cross-platform development is made simple and efficient by using JSON to store application parameters in Delphi. You may quickly store and retrieve application settings in JSON format with the aid of free and open source JSON components like SuperObject, DelphiJSON, and mORMot.

Related Posts

43 thoughts on “JSON in Delphi with examples

  1. Wow that was strange. I just wrote an really long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say superb blog!

  2. Oh my goodness! an amazing article dude. Thanks Nonetheless I’m experiencing problem with ur rss . Don抰 know why Unable to subscribe to it. Is there anybody getting equivalent rss drawback? Anybody who is aware of kindly respond. Thnkx

  3. Hi there! I know this is kinda off topic nevertheless
    I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa?
    My blg covers a lot of the same subjeccts as yours and
    I thik we could greatly benefit from each other.
    If you are interested feel free too shoot me an e-mail.
    I look forward to hearing from you! Terrific blog by the way! http://boyarka-Inform.com/

  4. I’ve been exploring for a bit for any high quality articles
    or blog posts on this sort of space . Exploring in Yahoo I at last stumbled upon this website.
    Studying this info So i am glad to show that I’ve an incredibly
    excellent uncanny feeling I found out exactly what I needed.

    I so much no doubt will make certain to don?t disregard this site and provides
    it a look regularly.

    Here is my homepage nordvpn Coupons Inspiresensation

  5. Great beat ! I wish to apprentice while you amend your web site,
    how could i subscribe for a blog website? The account helped
    me a acceptable deal. I had been tiny bit acquainted of this your broadcast
    offered bright clear concept

    Here is my web page; nordvpn coupons inspiresensation [easyurl.Cc]

  6. Hmm it looks like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what
    I wrote and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog blogger but I’m still new to the whole thing.
    Do you have any recommendations for first-time
    blog writers? I’d really appreciate it.

    My web site :: nordvpn coupons inspiresensation (tinyurl.com)

  7. Hi, I read your new stuff daily. Your story-telling style is awesome,
    keep doing what you’re doing!

    Also visit my website; nordvpn coupons inspiresensation (da.gd)

  8. Hiya, I’m really glad I have found this info. Today bloggers publish just about gossips and internet and this is really irritating. A good site with interesting content, this is what I need. Thanks for keeping this web site, I’ll be visiting it. Do you do newsletters? Can not find it.

  9. Excellent website you have here but I was curious if you knew of any discussion boards that cover the same topics talked about here? I’d really love to be a part of community where I can get advice from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Many thanks!

  10. I am really enjoying the theme/design of your weblog. Do you ever run into any browser compatibility problems? A few of my blog visitors have complained about my website not operating correctly in Explorer but looks great in Chrome. Do you have any advice to help fix this issue?

  11. Thanks for the tips shared in your blog. Something else I would like to mention is that fat loss is not supposed to be about going on a fad diet and trying to reduce as much weight as possible in a set period of time. The most effective way to burn fat is by taking it gradually and following some basic guidelines which can make it easier to make the most from a attempt to slim down. You may know and be following some of these tips, yet reinforcing information never hurts.

  12. Usually I don’t read post on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been surprised me. Thanks, very nice post.

  13. I do love the way you have framed this particular issue and it really does give us a lot of fodder for consideration. However, through everything that I have seen, I just hope when other feedback pack on that people keep on issue and don’t embark on a soap box involving the news of the day. Anyway, thank you for this fantastic piece and while I can not go along with it in totality, I regard your point of view.

  14. Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out much. I am hoping to present something again and help others such as you aided me.

  15. Thanks for your post right here. One thing I would really like to say is the fact that most professional areas consider the Bachelor’s Degree like thejust like the entry level requirement for an online education. Though Associate Diplomas are a great way to get started, completing your Bachelors starts up many entrances to various employment goodies, there are numerous online Bachelor Course Programs available coming from institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another concern is that many brick and mortar institutions present Online editions of their college diplomas but typically for a extensively higher charge than the institutions that specialize in online education plans.

  16. Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say excellent blog!

  17. I think that a foreclosures can have a significant effect on the client’s life. Property foreclosures can have a 7 to a decade negative effect on a applicant’s credit report. A new borrower having applied for home financing or any loans for that matter, knows that the worse credit rating is, the more hard it is to have a decent bank loan. In addition, it could affect the borrower’s capacity to find a good place to let or hire, if that becomes the alternative property solution. Great blog post.

  18. Thanks for your tips about this blog. One particular thing I would want to say is that purchasing electronic devices items through the Internet is nothing new. In truth, in the past decades alone, the market for online electronic products has grown a great deal. Today, you could find practically just about any electronic gadget and tools on the Internet, including cameras as well as camcorders to computer spare parts and gaming consoles.

  19. Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I’ll keep an eye out for your answers.

  20. Восстановление бампера автомобиля — это популярная услуга, которая позволяет обновить изначальный вид транспортного средства после незначительных повреждений. Новейшие технологии позволяют исправить сколы, трещины и вмятины без полной замены детали. При выборе между ремонтом или заменой бампера https://telegra.ph/Remont-ili-zamena-bampera-05-22 важно принимать во внимание степень повреждений и экономическую выгодность. Профессиональное восстановление включает шпатлевку, грунтовку и покраску.

    Замена бампера требуется при значительных повреждениях, когда восстановление бамперов невыгоден или невозможен. Расценки восстановления варьируется от материала изделия, характера повреждений и модели автомобиля. Синтетические элементы допускают ремонту лучше стальных, а новые композитные материалы требуют профессионального оборудования. Профессиональный ремонт увеличивает срок службы детали и обеспечивает заводскую геометрию кузова.

    С удовольствием бы предложить содействие по вопросам Замена бампера ваз 2104 – обращайтесь в Телеграм gbp03

  21. Thanks for your useful article. One other problem is that mesothelioma is generally brought on by the inhalation of fibres from mesothelioma, which is a dangerous material. It is commonly noticed among personnel in the engineering industry who have long contact with asbestos. It can also be caused by living in asbestos protected buildings for a long period of time, Your age plays an important role, and some individuals are more vulnerable for the risk than others.

Leave a Reply

Your email address will not be published. Required fields are marked *