Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


Working with JSON filter_list
Author
Message
Working with JSON #1
Using and storing configurable data outside of Java class files has never been a strong point of mine, so when I was working on a 2D Game Project of mine, I realised I would need a reliable, yet easy to read way of storying and retrieving data, such as the players name, password, and location.

I looked at many alternatives, the first one being straight binary, however even though this is the fastest choice, I didn't like the idea of having to write a tool to be able to directly edit it (well, at an efficient rate anyway). I also looked at XML, but I believe in comparison to some of the markup languages out today it's becoming outdated.

A friend of mine suggested I use JSON, and after looking into it, I became very fond of the way it was set out.

First off, you're going to need to download the JSON-Simple library. The may download it from this link here: JSON-Simple.

Next, you're going to need to create a JSON file. This can contain any data you wish to retrieve, but for reference sake and for this example, I'll provide one for you to use:
Code:
{
"username": "Chalant",
"password": "123",
"coordinates":["512","256","0"]
}

As you can see, this contains the variables username, password, and the x, y and z locations of my player, as well as the corresponding data for said variables.

So the first thing we want to do is actually create the class that will contain the methods for parsing and setting the data. If you're not using an IDE, you'll want to start by importing the required classes:
Code:
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

Now that's been done, we can proceed with the code functionality. First things first, you'll have to define three variables. The first two are strings, which will be containing our username and password, and the second is an array list, which will contain our coordinates:
Code:
/*
     * The variables we'll be retrieving from the
     * JSON configuration file.
     */
    private String username, password;
    private List<Integer> coordinates = new ArrayList<Integer>();

You'll also need to create a new instance of the JSON Parser, which is fairly obvious to do, but just in case you're unsure of how, here's the code:
Code:
/*
     * We create a new instance of the JSON Parser, which
     * is found in the JSON-Simple library.
     */
    private static final JSONParser PARSER = new JSONParser();

Now that our variables are defined, we're going to create getters and setters for them. This isn't required, but it makes the code much neater, and is good practice for conventions sake. This will contain methods to set the username, password, and also add coordinates to our list:
Code:
/*
     * We use these methods to set the data
     * that we earlier retrieved from our JSON file.
     */
    public void setUsername(String username) {
        this.username = username;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public void addCoordinate(int coordinate) {
        this.coordinates.add(coordinate);
    }

Similiarly, we're going to create methods to retrieve the data:
Code:
/*
     * These are the getters we will use for
     * grabbing the data from other classes.
     */
    public String getUsername() {
        return username;
    }
    
    public String getPassword() {
        return password;
    }
    
    public List<Integer> getCoordinates() {
        return this.coordinates;
    }

Now, onto the method that will parse the data from our JSON file. I've named my configuration file "chalant.json", and have placed it in a folder called data, located in my project's root directory. This is the method:
Code:
public void loadData() {
        try {
            /*
             * Here we tell our JSON Parser to parse the
             * file specified by the FileReader, and then
             * cast that to a JSON Object.
             */
            Object obj = PARSER.parse(new FileReader("data/chalant.json"));
            JSONObject jsonObject = (JSONObject) obj;
            
            /*
             * We use our variable setters (located below) to
             * assign local variables values that are defined in
             * our JSON configuration file, by casting their type
             * to the JSON Object.
             */
            setUsername((String) jsonObject.get("username"));
            setPassword((String) jsonObject.get("password"));
            
            /*
             * We parse through the array "coordinates" that is set
             * in our JSON file, and then iterate through all the values.
             * Then, we add the corresponding values to our ArrayList, defined
             * as "coordinates".
             */
            
            JSONArray coordinates = (JSONArray) jsonObject.get("coordinates");
            Iterator<String> iterator = coordinates.iterator();
            while (iterator.hasNext()) {
                addCoordinate(Integer.parseInt(iterator.next()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Hopefully I won't have to explain too much for that method, as I'm fairly sure I've documented it appropriately.

Finally, we want to create a main class. This will contain the code for initializing the above method, as well as retrieving and printing the variables.
Code:
public static void main(String[] args) {
        /* Here we are initializing our LoadData class,
         * which contains the methods for parsing JSON
         * data and storing the variables required.
         */
        LoadData getUserData = new LoadData();
        getUserData.loadData();

        /* Finally, we print out the value of the variables
         * that were set in our LoadData class
         */
        System.out.println("Username: " + getUserData.getUsername());
        System.out.println("Password: " + getUserData.getPassword());
        System.out.println("Coordinates: " + getUserData.getCoordinates());
    }

If you followed this correctly, all should have worked well. Feel free to post any questions you may have in regards to this tutorial. The full source code (including library and project) can be downloaded here: JSON Concepts

This was my first tutorial, so hopefully it wasn't too poorly written Smile

Reply

RE: Working with JSON #2
Wow, what a great tut !

Very helpful Smile
[Image: pQKMgUT.png]

Reply







Users browsing this thread: 2 Guest(s)