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

145 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.

  22. I really like your blog.. very nice colors & theme.
    Did you create this website yourself or did you hire someone to do it for you?

    Plz answer back as I’m looking to construct my own blog and
    would like to know where u got this from. appreciate it

    My website … vpn

  23. It’s really a nice and useful piece of info. I am glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

  24. In these days of austerity in addition to relative panic about taking on debt, a lot of people balk about the idea of using a credit card in order to make acquisition of merchandise and also pay for a holiday, preferring, instead just to rely on this tried plus trusted way of making transaction – cash. However, if you possess cash available to make the purchase completely, then, paradoxically, this is the best time for you to use the card for several reasons.

  25. An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

  26. I am curious to find out what blog platform you have been utilizing? I’m experiencing some small security issues with my latest blog and I’d like to find something more risk-free. Do you have any recommendations?

  27. Hey, you used to write great, but the last few posts have been kinda boring?I miss your great writings. Past few posts are just a little bit out of track! come on!

  28. Does your blog have a contact page? I’m having problems locating it but, I’d like to send you an email. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it improve over time.

  29. Neat blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog jump out. Please let me know where you got your theme. Bless you

  30. Fantastic goods from you, man. I’ve understand your stuff previous to and you’re just too excellent. I really like what you’ve acquired here, certainly like what you are stating and the way in which you say it. You make it entertaining and you still care for to keep it wise. I can’t wait to read far more from you. This is really a tremendous site.

  31. Good – I should definitely pronounce, impressed with your website. I had no trouble navigating through all the tabs and related info ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your client to communicate. Excellent task..

  32. Hello there, just became aware of your blog through Google, and found that it is truly informative. I’m going to watch out for brussels. I will be grateful if you continue this in future. A lot of people will be benefited from your writing. Cheers!

  33. As I site possessor I believe the content material here is rattling wonderful , appreciate it for your efforts. You should keep it up forever! Best of luck.

  34. Thanks for the recommendations you have provided here. One more thing I would like to convey is that laptop memory demands generally go up along with other advancements in the technological know-how. For instance, any time new generations of processor chips are made in the market, there is certainly usually an equivalent increase in the dimensions demands of all laptop or computer memory and hard drive space. This is because the program operated through these processor chips will inevitably surge in power to leverage the new know-how.

  35. Have you ever considered writing an ebook or guest authoring on other websites? I have a blog centered on the same information you discuss and would love to have you share some stories/information. I know my subscribers would appreciate your work. If you are even remotely interested, feel free to send me an e mail.

  36. I have discovered some new things from your web page about pc’s. Another thing I’ve always believed is that computers have become a specific thing that each family must have for several reasons. They offer convenient ways to organize homes, pay bills, shop, study, tune in to music and also watch television shows. An innovative method to complete these types of tasks is a laptop. These desktops are mobile ones, small, robust and transportable.

  37. Hey would you mind sharing which blog platform you’re working with?
    I’m looking to start my own blog in the near future but I’m having a difficult time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m
    looking for something unique.
    P.S Sorry for being off-topic but I had to ask!

  38. I do trust all of the concepts you have presented for your post. They’re really convincing and will definitely work. Nonetheless, the posts are very quick for novices. May just you please lengthen them a little from subsequent time? Thanks for the post.

  39. I was wondering if you ever considered changing the layout of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 pictures. Maybe you could space it out better?

  40. Hmm it appears like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to the whole thing. Do you have any points for novice blog writers? I’d really appreciate it.

  41. I haven抰 checked in here for some time since I thought it was getting boring, but the last several posts are great quality so I guess I抣l add you back to my everyday bloglist. You deserve it my friend 🙂

  42. Yesterday, while I was at work, my sister stole my
    apple ipad and tested to see if it can survive a forty foot drop, just so she can be a youtube sensation. My apple
    ipad is now destroyed and she has 83 views. I know this is
    totally off topic but I had to share it with someone!

  43. Have you ever thought about adding a little bit
    more than just your articles? I mean, what you say is
    fundamental and all. But think about if you added some great visuals
    or video clips to give your posts more, “pop”!
    Your content is excellent but with images and clips, this website could undeniably be one of the greatest in its niche.
    Very good blog!

Leave a Reply

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