When data is send over a network, it can be done with different text formats, for example, XML, YAML or JSON. In this post we will use JSON, which is a simple text, based on the syntax of the JavaScript object. Within a JSON text file we can define basic data types such as strings, matrices, numbers, booleans and other literals.

A common practice is to parse a JSON, either to extract the data from it or insert it. In this case we will focus on a problem that was originated with the ordered insertion of fields in a JSON from a data structure (matrix …) in Java with the json.simple library.

It turns out that when we want to have the fields inside a JSON file in a specific order,  but Java does not allow us to establish that order. In other words, when defining an array with some sorted fields that we will go through and at the same time inserting the information in a JSON file, this ordered insertion of fields in the JSON will not be fulfilled, but then the fields are reordered in the JSON in a random way. In the following image you can see an example.

 

To solve this requirement, a modification of the original library Json.simple had to be made. And for this it was necessary to download the source code of the library that is on the version control platform github. Then the collection of objects HasMap, had to be modified (that does not have a predefined order) with a LinkedHasMap (yes he does) that allows us to insert the fields in the JSON file in an orderly manner.

Below is shown un example made with the intellij IDE in Java:

  1. Initial order of the matrix that we want to insert in a JSON
String[] header={"Name","Surname","Country","State","City", "Address"};
String[] content={"Alex","Alexiades","Tazmania","Taz","Diablo", "Crazy Ave"}; 
  1. Result of the parsing of the array with the unmodified json-simple library:

2.1/ Maven dependency

 <dependencies>
 <dependency>
 <groupId>com.googlecode.json-simple</groupId>
 <artifactId>json-simple</artifactId>
 <version>1.1.1</version>
 </dependency
 </dependencies>

2.2/ Result of JSON

 {
   "Address":"Crazy Ave",
   "State":"Taz",
   "Country":"Tazmania",
   "City":"Diablo",
   "Surname":"Alexiades",
   "Name":"Alex"
 }

  1. Substitution of the original library by the modified json-simple.jar

3.1 The first thing we have to do is to delete the maven dependencies from the original JSON library and then add the modify library that we will save in a project directory, for example the lib directory.

3.2 Result of the JSON file with the modify json-simple.jar library

 {
   "Name":"Alex",
   "Surname":"Alexiades",
   "Country":"Tazmania",
   "State":"Taz",
   "City":"Diablo",
   "Address":"Crazy Ave",
 }

For more information or  to download the modified library, you can do it in the following link github.

 

Alejandro Alexiades Estarriol