Fractal Softworks Forum

Please login or register.

Login with username, password and session length

Author Topic: How To: use JSONArray(s)/JSONObject(s) from custom *.json files.  (Read 2618 times)

silentstormpt

  • Admiral
  • *****
  • Posts: 1060
    • View Profile
How To: use JSONArray(s)/JSONObject(s) from custom *.json files.
« on: September 16, 2013, 01:24:27 PM »

So one of the big changes we got now, is the possibility of having our own custom *.json files with all the static data we need without having to resort creating massive Arrays/ArrayLists/Hash...etc.

So how do they work?

First of all, you should check the website www.json.org it gives you a very detailed explanation of what data and format can you expect from a *.json file.

There are 2 formats that can be inside each other, a JSONObject that can have a JSONArray(s), JSONObject(s) or data inside (or even all mixed in), or a JSONArray that can have more JSONArray(s) or more JSONObject(s) (or even both mixed in). Knowing the format is extremely important to extract certain type of data in the JSONObject.

How you do know whats an JSONArray and whats a JSONObject?

Heres a example (battle_objectives.json):
{
   "nav_buoy":{
      "name":"Nav Buoy",
      "icon":"graphics/warroom/objective_nav_buoy.png",
      "sprite":"graphics/ships/nav_buoy.png",
      "spriteScale":1.5,
      "captureTime":10,
      "effectClass":"com.fs.starfarer.api.impl.combat.NavBuoyEffect",
   },
   "sensor_array":{
      "name":"Sensor Array",
      "icon":"graphics/warroom/objective_sensor_array.png",
      "sprite":"graphics/ships/sensor_array.png",
      "spriteScale":1,
      "captureTime":10,
      "effectClass":"com.fs.starfarer.api.impl.combat.SensorArrayEffect",
   },
   "comm_relay":{
      "name":"Comm Relay",
      "icon":"graphics/warroom/objective_comm_relay.png",
      "sprite":"graphics/ships/com_relay.png",
      "spriteScale":1,
      "captureTime":10,
      "effectClass":"com.fs.starfarer.api.impl.combat.CommRelayEffect",
   },
}
In red and orange, inside the {} are JSONObjects, but you can have more JSONObjects inside a JSONObject.
The main JSONObject (the one thats got everything inside the orange {}'s) has 3 JSONObjects. These have (can also not have) identifiers as a text in the green ""'s, if you only want a specific JSONObject, you get the id in the "", if you want a specific data value inside the JSONObject, you use the id in the ""'s (not the green one).

JSONArray starts with []'s instead, and are just like what you expect on a Array,

Heres a small example (sounds.json):
{
   "music":{
      # "source" can also be a directory
      "music_campaign":[
         {"file":"StianStark-Starfarer-Exploration_Alpha.ogg","source":"sounds/music/music.bin"}
      ],
      "music_title":[
         {"file":"StianStark-Starfarer-Exploration_Alpha.ogg","source":"sounds/music/music.bin"}
      ],
      "music_combat":[
         {"file":"battle_ambience_01_v02_loudest.ogg","source":"sounds/music/music.bin"}
      ],
   }
}

In this particular case we got a JSONObject thats got several (if i pasted all the sounds.json, not true on this piece of json) JSONObjects and each of these got one or more JSONArray(s) and finally we got JSONObject inside each JSONArray with no identifier. Just like on the first example you got the identifiers for each JSONObject and now on JSONArray as well.

Heres a cool way to understand the format of this example:

JSONObject
{
Spoiler
   JSONObject
   {
   
Spoiler
      JSONArray
      [
     
Spoiler
         {
         JSONObject
         }
     
[close]
      ]
   
[close]
   }
[close]
Spoiler
   JSONObject
   {
   
Spoiler
      JSONArray
      [
     
Spoiler
         {
         JSONObject
         }
     
[close]
      ]
   
[close]
   }
[close]
Spoiler
   JSONObject
   {
   
Spoiler
      JSONArray
      [
     
Spoiler
         {
         JSONObject
         }
     
[close]
      ]
   
[close]
   }
[close]
}

Now how do i use it on the game itself?

To get a json from you game folder you need something like this:
Code
JSONArray jarray = new JSONArray(JSON_FILE_URL);
or
Code
JSONObject jobject = new JSONObject(JSON_FILE_URL);

It will ask to set up a Try{}Catch{} since your asking for a file that may or may not exist in that URL/Directory

Once done, depending on how the json file format composition is, lets use the second example as the file we want the data:
Code
        try {
            JSONObject jobject = new JSONObject(JSON_FILE_URL);
        } catch (JSONException ex) {
            //set the default log message here including the ex (Exception)
            Logger.getLogger(SectorGen.class.getName()).log(Level.SEVERE, null, ex);
        }

if(jobject != null)
{
        for(int i = 0; i < jobject.length();i++)
        {
            //grab this jsonobject in the list
            JSONObject jobj = jobject.getJSONObject(i);
            for(int x = 0;x < jobj.length();x++)
            {
               JSONArray jarray = jobj.getJSONArray(x);
               for(int a = 0; a < jarray.length();a++)
               {
               JSONObject jlastobj = jarray.getJSONObject(a);
                  for(int l = 0; l < jlastobj.length();l++)
                  {
                  //get this value on this line into stringdata arraylist
                  stringdata.add(jlastobj.getString("file"));
                  stringdata.add(jlastobj.getString("source"));
                  }
               }
        }
}

This should save all the strings inside the "file":"" and "source":"".

All you do is Open the next "container" until you reach what you want.
You can also get a specific data from a JSONObject/Array with a certain ID.
« Last Edit: September 16, 2013, 05:33:33 PM by silentstormpt »
Logged