org.json - Guide rapide

org.json or JSON-Javaest une boîte à outils Java simple pour JSON. Vous pouvez utiliser org.json pour encoder ou décoder des données JSON.

traits

  • Specification Compliant - JSON.simple est entièrement conforme à la spécification JSON - RFC4627.

  • Lightweight - Il a très peu de classes et fournit les fonctionnalités nécessaires comme encoder / décoder et échapper json.

  • XML Conversion - Il fournit une capacité de conversion de JSON en XML et vice-versa.

  • HTTP Headers - Prend en charge la conversion de l'en-tête HTTP en JSON et vice versa.

  • Cookie - Fournit un support pour la conversion des cookies en JSON et vice versa.

  • CDL - Fournit un support pour convertir une liste séparée par des virgules en JSON et vice versa.

  • No dependency- Aucune dépendance de bibliothèque externe. Peut être inclus indépendamment.

  • Java 1.6-1.8 compatible - Le code source et le binaire sont compatibles Java 1.6-1.8

Configuration de l'environnement local

JSON.simple est une bibliothèque pour Java, donc la toute première exigence est d'avoir JDK installé sur votre machine.

Exigence du système

JDK 1.5 ou supérieur.
Mémoire Aucune exigence minimale.
Espace disque Aucune exigence minimale.
Système opérateur Aucune exigence minimale.

Étape 1: Vérifiez l'installation de Java sur votre machine

Tout d'abord, ouvrez la console et exécutez une commande java basée sur le système d'exploitation sur lequel vous travaillez.

OS Tâche Commander
les fenêtres Ouvrez la console de commande c: \> java -version
Linux Ouvrir le terminal de commande $ java -version
Mac Terminal ouvert machine: <joseph $ java -version

Vérifions la sortie pour tous les systèmes d'exploitation -

OS Production
les fenêtres

version java "1.8.0_101"

Environnement d'exécution Java (TM) SE (build 1.8.0_101)

Linux

version java "1.8.0_101"

Environnement d'exécution Java (TM) SE (build 1.8.0_101)

Mac

version java "1.8.0_101"

Environnement d'exécution Java (TM) SE (build 1.8.0_101)

Si Java n'est pas installé sur votre système, téléchargez le kit de développement logiciel Java (SDK) à partir du lien suivant www.oracle.com . Nous supposons que Java 1.8.0_101 est la version installée pour ce didacticiel.

Étape 2: définir l'environnement JAVA

Met le JAVA_HOMEvariable d'environnement pour pointer vers l'emplacement du répertoire de base où Java est installé sur votre machine. Par exemple.

OS Production
les fenêtres Définissez la variable d'environnement JAVA_HOME sur C: \ Program Files \ Java \ jdk1.8.0_101
Linux export JAVA_HOME = / usr / local / java-current
Mac export JAVA_HOME = / Bibliothèque / Java / Accueil

Ajoutez l'emplacement du compilateur Java au chemin système.

OS Production
les fenêtres Ajouter la chaîne C:\Program Files\Java\jdk1.8.0_101\bin à la fin de la variable système, Path.
Linux export PATH = $ PATH: $ JAVA_HOME / bin /
Mac non requis

Vérifiez l'installation de Java à l'aide de la commande java -version comme expliqué ci-dessus.

Étape 3: Téléchargez l'archive org.json

Téléchargez la dernière version du fichier jar org.json à partir de org.json @ MVNRepository . Au moment de la rédaction de ce didacticiel, nous avons téléchargé json-20180813 et l'avons copié dans le dossier C: \> JSON.

OS Nom de l'archive
les fenêtres json-20180813.jar
Linux json-20180813.jar
Mac json-20180813.jar

Étape 4: définir l'environnement JSON_JAVA

Met le JSON_JAVAvariable d'environnement pour pointer vers l'emplacement du répertoire de base où le jar org.json est stocké sur votre machine. Supposons que nous ayons stocké json-20180813.jar dans le dossier JSON.

Sr. Non OS et description
1

Windows

Définissez la variable d'environnement JSON_JAVA sur C: \ JSON

2

Linux

exporter JSON_JAVA = / usr / local / JSON

3

Mac

export JSON_JAVA = / Bibliothèque / JSON

Étape 5: Définissez la variable CLASSPATH

Met le CLASSPATH variable d'environnement pour pointer vers l'emplacement du fichier JSON.simple.

Sr. Non OS et description
1

Windows

Définissez la variable d'environnement CLASSPATH sur% CLASSPATH%;% JSON_JAVA% \ json-20180813.jar;.;

2

Linux

export CLASSPATH = $ CLASSPATH: $ JSON_JAVA / json-20180813.jar :.

3

Mac

export CLASSPATH = $ CLASSPATH: $ JSON_JAVA / json-20180813.jar :.

La classe CDL fournit des méthodes statiques pour convertir un texte délimité par des virgules en JSONArray, et vice versa.

Les méthodes suivantes sont couvertes dans l'exemple.

  • rowToJSONArray(String) - Convertit un texte délimité par des virgules en objet JSONArray.

  • rowToString(JSONArray) - Convertit un JSONArray en texte délimité par des virgules.

  • toJSONArray(String) - Convertit un texte délimité par des virgules sur plusieurs lignes en objet d'objets JSONArray.

  • toJSONArray(JSONArray, String) - Convertit un objet JSONArray et un texte délimité par des virgules en objet JSONArray.

Exemple

import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;

public class JSONDemo {
   public static void main(String[] args) {
      String csvData = "INDIA, UK, USA";

      //Case 1: CSV to JSON Array 
      JSONArray jsonArray = CDL.rowToJSONArray(new JSONTokener(csvData));        
      System.out.println(jsonArray);

      //Case 2: JSONArray to CSV        
      System.out.println(CDL.rowToString(jsonArray));

      //Case 3: CSV to JSONArray of Objects
      csvData = "empId, name, age \n" +
         "1, Mark, 22 \n" +
         "2, Robert, 35 \n" +
         "3, Julia, 18";
      System.out.println(CDL.toJSONArray(csvData));

      //Case 4: CSV without header        
      jsonArray = new JSONArray();
      jsonArray.put("empId");
      jsonArray.put("name");
      jsonArray.put("age");
      csvData = "1, Mark, 22 \n" + "2, Robert, 35 \n" + "3, Julia, 18";
      System.out.println(CDL.toJSONArray(jsonArray,csvData));
   }
}

Production

["INDIA","UK","USA"]
INDIA,UK,USA

[{"name":"Mark","empId":"1","age":"22"},
   {"name":"Robert","empId":"2","age":"35"},
   {"name":"Julia","empId":"3","age":"18"}]
[{"name":"Mark","empId":"1","age":"22"},
   {"name":"Robert","empId":"2","age":"35"},
   {"name":"Julia","empId":"3","age":"18"}]

La classe Cookie fournit des méthodes statiques pour convertir le texte du cookie du navigateur Web en JSONObject, et vice versa.

Les méthodes suivantes sont couvertes dans l'exemple.

  • toJSONObject(String) - Convertit un texte de cookie en objet JSONObject.

  • toString(JSONObject) - Convertit un JSONObject en texte de cookie.

Exemple

import org.json.Cookie;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      String cookie = "username = Mark Den; expires = Thu, 15 Jun 2020 12:00:00 UTC; path = /";

      //Case 1: Converts Cookie String to JSONObject
      JSONObject jsonObject = Cookie.toJSONObject(cookie);
      System.out.println(jsonObject);

      //Case 2: Converts JSONObject to Cookie String
      System.out.println(Cookie.toString(jsonObject));        
   }
}

Production

{"path":"/","expires":"Thu, 15 Jun 2020 12:00:00 UTC","name":"username","value":"Mark Den"}
username=Mark Den;expires=Thu, 15 Jun 2020 12:00:00 UTC;path=/

La classe CookieList fournit des méthodes statiques pour convertir la liste de cookies en JSONObject, et vice versa. La liste des cookies est une séquence de paires nom / valeur.

Les méthodes suivantes sont couvertes dans l'exemple.

  • toJSONObject(String) - Convertit un texte de liste de cookies en objet JSONObject.

  • toString(JSONObject) - Convertit un JSONObject en texte de liste de cookies.

Exemple

import org.json.Cookie;
import org.json.CookieList;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      String cookie = "username = Mark Den; expires = Thu, 15 Jun 2020 12:00:00 UTC; path = /";

      //Case 1: Converts Cookie String to JSONObject
      JSONObject cookieJSONObject = Cookie.toJSONObject(cookie);

      JSONObject cookielistJSONObject = new JSONObject();       
      cookielistJSONObject.put(cookieJSONObject.getString("name"), 
         cookieJSONObject.getString("value"));       

      String cookieList = CookieList.toString(cookielistJSONObject);        
      System.out.println(cookieList); 
      System.out.println(CookieList.toJSONObject(cookieList));
   }
}

Production

username=Mark Den
{"username":"Mark Den"}

La classe HTTP fournit des méthodes statiques pour convertir le texte d'en-tête du navigateur Web en un JSONObject, et vice versa.

Les méthodes suivantes sont couvertes dans l'exemple.

  • toJSONObject(String) - Convertit un texte d'en-tête en objet JSONObject.

  • toString(JSONObject) - Convertit un JSONObject en texte d'en-tête.

Exemple

import org.json.HTTP;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Method", "POST");
      jsonObject.put("Request-URI", "http://www.tutorialspoint.com/");
      jsonObject.put("HTTP-Version", "HTTP/1.1");
        
      //Case 1: Converts JSONObject of Header to String
      String headerText = HTTP.toString(jsonObject);
      System.out.println(headerText); 
        
      headerText = "POST \"http://www.tutorialspoint.com/\" HTTP/1.1";
      //Case 2: Converts Header String to JSONObject
      System.out.println(HTTP.toJSONObject(headerText));
   }
}

Production

POST "http://www.tutorialspoint.com/" HTTP/1.1

{"Request-URI":"http://www.tutorialspoint.com/","Method":"POST","HTTP-Version":"HTTP/1.1"}

Un JSONArray est une séquence ordonnée de valeurs. Il fournit des méthodes pour accéder aux valeurs par index et pour mettre des valeurs. Les types suivants sont pris en charge -

  • Boolean

  • JSONArray

  • JSONObject

  • Number

  • String

  • Objet JSONObject.NULL

Exemple

import org.json.JSONArray;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) { 
      JSONArray list = new JSONArray();

      list.put("foo");
      list.put(new Integer(100));
      list.put(new Double(1000.21));
      list.put(new Boolean(true));
      list.put(JSONObject.NULL);

      System.out.println("JSONArray: ");
      System.out.println(list);
   }
}

Production

JSONArray: 
["foo",100,1000.21,true,null]

La classe JSONML fournit des méthodes statiques pour convertir un texte XML en JSONArray, et vice versa.

Les méthodes suivantes sont couvertes dans l'exemple.

  • toJSONArray(String) - Convertit un XML en objet JSONArray.

  • toJSONObject(String) - Convertit un XML en objet JSONObject.

  • toString(JSONArray) - Donne un XML à partir d'un objet JSONArray.

  • toString(JSONObject) - Donne un XML à partir d'un objet JSONObject.

Exemple

import org.json.JSONArray;
import org.json.JSONML;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      JSONArray list = new JSONArray();
      list.put("name");
      list.put("Robert");     

      System.out.println("XML from a JSONArray: ");
      String xml = JSONML.toString(list);
      System.out.println(xml);

      System.out.println("JSONArray from a XML: ");
      list = JSONML.toJSONArray(xml);
      System.out.println(list);

      System.out.println("JSONObject from a XML: ");
      JSONObject object = JSONML.toJSONObject(xml);
      System.out.println(object);

      System.out.println("XML from a JSONObject: ");
      xml = JSONML.toString(object);
      System.out.println(xml);
   }
}

Production

XML from a JSONArray: 
<name>Robert</name>
JSONArray from a XML: 
["name","Robert"]
JSONObject from a XML: 
{"childNodes":["Robert"],"tagName":"name"}
XML from a JSONObject: 
<name>Robert</name>

La classe JSONObject est une collection non ordonnée de paires clé-valeur. Il fournit des méthodes pour accéder aux valeurs par clé et pour mettre des valeurs. Les types suivants sont pris en charge -

  • Boolean

  • JSONArray

  • JSONObject

  • Number

  • String

  • Objet JSONObject.NULL

Exemple

import org.json.JSONArray;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", new Double(1000.21));
      jsonObject.put("Active", new Boolean(true));
      jsonObject.put("Other Details", JSONObject.NULL);

      JSONArray list = new JSONArray();
      list.put("foo");
      list.put(new Integer(100));
      jsonObject.put("list",list);
      System.out.println(jsonObject);
   }
}

Production

{"Active":true,"Other Details":null,"ID":1,"Fees":1000.21,"list":["foo",100],"Name":"Robert"}

JSONStringer est une classe utilitaire pour créer rapidement un texte JSON qui confirme les règles de syntaxe JSON. Chaque instance de JSONStringer peut produire un texte JSON.

Exemple

import org.json.JSONStringer;

public class JSONDemo {
   public static void main(String[] args) { 
      String jsonText = new JSONStringer()
         .object()
         .key("Name")
         .value("Robert")                            
         .endObject()                       
         .toString();
      System.out.println(jsonText);

      jsonText = new JSONStringer()
         .array()
         .value("Robert")      
         .value("Julia")      
         .value("Dan")
         .endArray()                       
         .toString();
      System.out.println(jsonText);

      jsonText = new JSONStringer()
         .array()
         .value("Robert")      
         .value("Julia")      
         .value("Dan")
         .object()
         .key("Name")
         .value("Robert")                            
         .endObject()  
         .endArray()             
         .toString();
      System.out.println(jsonText);
   }
}

Production

{"Name":"Robert"}
["Robert","Julia","Dan"]
["Robert","Julia","Dan",{"Name":"Robert"}]

La classe Property fournit des méthodes statiques pour convertir le texte des propriétés en JSONObject, et vice versa.

Les méthodes suivantes sont couvertes dans l'exemple.

  • toJSONObject(Properties) - Convertit les données de propriétés en objet JSONObject.

  • toProperties(JSONObject) - Convertit un JSONObject en objet de propriétés.

Exemple

import java.util.Properties;
import org.json.JSONObject;
import org.json.Property;

public class JSONDemo {
   public static void main(String[] args) {
      Properties properties = new Properties();
      properties.put("title", "This is a title text");
      properties.put("subtitle", "This is a subtitle text");

      System.out.println("Properties to JSON");
      JSONObject jsonObject = Property.toJSONObject(properties);
      System.out.println(jsonObject);

      System.out.println("JSON to properties");
      System.out.println(Property.toProperties(jsonObject));
   }
}

Production

Properties to JSON
{"subtitle":"This is a subtitle text","title":"This is a title text"}
JSON to properties
{subtitle = This is a subtitle text, title = This is a title text}

La classe XML fournit des méthodes statiques pour convertir un texte XML en JSONObject, et vice versa.

Les méthodes suivantes sont couvertes dans l'exemple.

  • toJSONObject(String) - Convertit un XML en objet JSONArray.

  • toString(JSONObject) - Donne un XML à partir d'un objet JSONObject.

Exemple

import org.json.JSONObject;
import org.json.XML;

public class JSONDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", new Double(1000.21));
      jsonObject.put("Active", new Boolean(true));
      jsonObject.put("Details", JSONObject.NULL);

      //Convert a JSONObject to XML
      String xmlText = XML.toString(jsonObject);
      System.out.println(xmlText);

      //Convert an XML to JSONObject
      System.out.println(XML.toJSONObject(xmlText));
   }
}

Production

<Active>true</Active><Details>null</Details><ID>1</ID><Fees>1000.21</Fees><Name>Robert</Name>
{"Active":true,"Details":null,"ID":1,"Fees":1000.21,"Name":"Robert"}

Les classes utilitaires de org.json lèvent JSONException en cas de JSON non valide. L'exemple suivant montre comment gérer JSONException.

Exemple

import org.json.JSONException;
import org.json.XML;

public class JSONDemo {
   public static void main(String[] args) {
      try{
         //XML tag name should not have space.
         String xmlText = "<Other Details>null</Other Details>";
         System.out.println(xmlText);

         //Convert an XML to JSONObject
         System.out.println(XML.toJSONObject(xmlText));
      } catch(JSONException e){   
         System.out.println(e.getMessage());
      }
   }
}

Production

position: 24
Unexpected token RIGHT BRACE(}) at position 24.