Search code examples
iosjsonswift

Big JSON file in Swift


I need help with one file "citylist.json". This file is 29 MB and if I try to add it to my Swift project, my laptop takes 10 mins just to load the file.

Is there any solution that works with a big JSON file with Swift? I need to use this JSON file online or remote.

I'm working with the weather API and when I need to find the city by typing the name sometimes the app crash down because what you write is not conform with the weather API. the company what provided me the API, advice everyone need to find city by use the city code and inside on my JSON file there a list of all cities with the code. This is the reason why I need to work with this file.


Solution

  • JSONSerialization is slow. There is two possible solutions.

    1. Use database:

      • Add database support to your app
      • Convert JSON to database format
      • Search through database instead of JSON
    2. Split one JSON into several files, based on first two (or three) letters from City name.

    Let's say you have JSON with structure:

    {
        cities: [
          ...,
          Berlin: {},
          ...,
            Monako: {},
            Moscow: {},
            ...,
        ],
    }
    

    You can split it to many JSON files with two letters names, example for file mo.json:

    {
        cities: [
          ...,
            Monako: {},
            Moscow: {},
            ...,
        ],
    }
    

    That way you can speed up the process of serialization.

    • You search for the appropriate file in you bundle
    • You search for all city that fits your query
    • For example: query Mos will search mo.json and show Moscow, but not Monako.