Org json jsonobject java maven

JSON.simple – Read and Write JSON

JSON.simple is a lightweight JSON processing library that can be used to read and write JSON files and strings. The encoded/decoded JSON will be in full compliance with JSON specification (RFC4627).

JSON.simple library is pretty old and has not been updated since march, 2012. Google GSON library is a good option for reading and writing JSON.

In this Java JSON tutorial, we will first see a quick example of writing to a JSON file and then we will read JSON from the file.

  • Full compliance with JSON specification (RFC4627).
  • Supports encode, decode/parse and escape JSON.
  • Easy to use by reusing Map and List interfaces.
  • Supports streaming output of JSON text.
  • High performance.
  • No dependency on external libraries.
Читайте также:  Docker php cli log

Update pom.xml with json-simple maven dependency.

 com.googlecode.json-simple json-simple 1.1.1 

To write JSON test into the file, we will be working with mainly two classes:

  1. JSONArray : To write data in json arrays. Use its add() method to add objects of type JSONObject .
  2. JSONObject : To write json objects. Use it’s put() method to populate fields.

After populating the above objects, use FileWriter instance to write the JSON file.

package com.howtodoinjava.demo.jsonsimple; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class WriteJSONExample < @SuppressWarnings("unchecked") public static void main( String[] args ) < //First Employee JSONObject employeeDetails = new JSONObject(); employeeDetails.put("firstName", "Lokesh"); employeeDetails.put("lastName", "Gupta"); employeeDetails.put("website", "howtodoinjava.com"); JSONObject employeeObject = new JSONObject(); employeeObject.put("employee", employeeDetails); //Second Employee JSONObject employeeDetails2 = new JSONObject(); employeeDetails2.put("firstName", "Brian"); employeeDetails2.put("lastName", "Schultz"); employeeDetails2.put("website", "example.com"); JSONObject employeeObject2 = new JSONObject(); employeeObject2.put("employee", employeeDetails2); //Add employees to list JSONArray employeeList = new JSONArray(); employeeList.add(employeeObject); employeeList.add(employeeObject2); //Write JSON file try (FileWriter file = new FileWriter("employees.json")) < //We can write any JSONArray or JSONObject instance to the file file.write(employeeList.toJSONString()); file.flush(); >catch (IOException e) < e.printStackTrace(); >> >

To read JSON from file, we will use the JSON file we created in the previous example.

  1. First of all, we will create JSONParser instance to parse JSON file.
  2. Use FileReader to read JSON file and pass it to parser.
  3. Start reading the JSON objects one by one, based on their type i.e. JSONArray and JSONObject .
package com.howtodoinjava.demo.jsonsimple; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ReadJSONExample < @SuppressWarnings("unchecked") public static void main(String[] args) < //JSON parser object to parse read file JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("employees.json")) < //Read JSON file Object obj = jsonParser.parse(reader); JSONArray employeeList = (JSONArray) obj; System.out.println(employeeList); //Iterate over employee array employeeList.forEach( emp ->parseEmployeeObject( (JSONObject) emp ) ); > catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (ParseException e) < e.printStackTrace(); >> private static void parseEmployeeObject(JSONObject employee) < //Get employee object within list JSONObject employeeObject = (JSONObject) employee.get("employee"); //Get employee first name String firstName = (String) employeeObject.get("firstName"); System.out.println(firstName); //Get employee last name String lastName = (String) employeeObject.get("lastName"); System.out.println(lastName); //Get employee website name String website = (String) employeeObject.get("website"); System.out.println(website); >>
[ >, > ] Lokesh Gupta howtodoinjava.com Brian Schultz example.com

Источник

Читайте также:  Javascript document forms form name

Пример работы с JSON.org в Java: разбор и создание JSON

Обработка JSON с помощью orgJSON в Java

Эта статья является продолжением серии статей по работе с Json в Java. В прошлой статье мы разобрались с Json Simple API на примере, а в этой статье мы познакомимся с достаточно простым и удобным способом обработки Json в Java под названием JSON.org.

JSON.org — это одна из первых open source библиотек для работы с JSON в Java. Она достаточно проста в использовании, однако не является самой гибкой и быстрой из существующих.

Обзор библиотеки JSON.org

JSON.org содержит классы для разбора и создания JSON из обычной Java-строки. Также она имеет возможность преобразовывать JSON в XML, HTTP header, Cookies и многое другое.

Основу этой библиотеки составляют следующие классы:

  1. Класс org.json.JSONObject — хранит неупорядоченные пары типа ключ — значение. Значение могут быть типа String, JSONArray, JSONObject.NULL, Boolean и Number . Класс JSONObject также содержит конструкторы для конвертации Java-строки в JSON и дальнейшего ее разбора в последовательность ключ-значений.
  2. Класс org.json.JSONTokener используется для разбора JSON строки, а также используется внутри классов JSONObject и JSONArray
  3. Класс org.json.JSONArray хранит упорядоченную последовательность значений в виде массива JSON элементов.
  4. Класс org.json.JSONWriter представляет возможность получения Json. Он содержит такие полезные в работе методы, как append(String) — добавить строку в JSON текст, key(String) и value(String) методы для добавления ключа и значения в JSON строку. Также org.json.JSONWriter умеет записывать массив.
  5. org.json.CDL — этот класс содержит методы для преобразования значений, разделенных запятыми, в объекты JSONArray и JSONArray.
  6. Класс org.json.Cookie располагает методами для преобразования файлов cookie веб-браузера в JSONObject и обратно.
  7. Класс org.json.CookieList помогает преобразовать список куки в JSONObject и обратно.

Добавление библиотеки json.org в проект

Для удобства я использовал среду разработки Intellij IDEA Community Edition. Если Вы не хотите создавать maven проект, то можете создать простой проект и вручную добавить .jar библиотеку в проект. Создадим maven проект и добавим в зависимости библиотеку org.json. Фрагмент файла pom.xml с зависимостями у меня выглядит следующим образом:

Источник

org.json : json

JSON in Java · JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ The files in this package implement JSON encoders/decoders in Java. It also includes the capability to convert between JSON and XML, HTTP headers, Cookies, and CDL. This is a reference implementation. There is a large number of JSON packages in Java. Perhaps someday the Java community will standardize on one. Until then, choose carefully.

dependency> groupId>org.jsongroupId> artifactId>jsonartifactId> version>20230618version> dependency> 
// https://mavenlibs.com/maven/dependency/org.json/jsonimplementation group: 'org.json', name: 'json', version: '20230618'
// https://mavenlibs.com/maven/dependency/org.json/jsonimplementation 'org.json:json:20230618'
// https://mavenlibs.com/maven/dependency/org.json/jsonimplementation("org.json:json:20230618")
// https://mavenlibs.com/maven/dependency/org.json/jsonlibraryDependencies += "org.json" % "json" % "20230618"
// https://mavenlibs.com/maven/dependency/org.json/json@Grapes( @Grab(group='org.json', module='json', version='20230618') )
;; https://mavenlibs.com/maven/dependency/org.json/json[org.json/json "20230618"]
# https://mavenlibs.com/maven/dependency/org.json/json'org.json:json:jar:20230618'

Latest Version

Choose a version of org.json : json to add to Maven or Gradle — Latest Versions:

All Versions

Choose a version of org.json : json to add to Maven or Gradle — All Versions:

Источник

json-simple example

json-simple example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

json-simple is a simple java toolkit for JSON. json-simple library is fully compliance with JSON specification (RFC4627).

json-simple

json-simple, json simple example, json example

json-simple uses Map and List internally for JSON processing. We can use json-simple for parsing JSON data as well as writing JSON to file. One of the best feature of json-simple is that it has no dependency on any third party libraries. json-simple is very lightweight API and serves well with simple JSON requirements.

json-simple maven

We can add json-simple library to our project by downloading it from here. Since json-simple is available in maven central repository, best way is to add it’s dependency in pom.xml file.

 com.googlecode.json-simple json-simple 1.1.1  

json-simple example to write JSON to file

Most important class in json-simple API is org.json.simple.JSONObject . We create instance of JSONObject and put key-value pairs into it. JSONObject toJSONString method returns the JSON in String format that we can write to file. For writing list to a JSON key, we can use org.json.simple.JSONArray .

package com.journaldev.json.write; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class JsonSimpleWriter < @SuppressWarnings("unchecked") public static void main(String[] args) < JSONObject obj = new JSONObject(); obj.put("name", "Pankaj Kumar"); obj.put("age", new Integer(32)); JSONArray cities = new JSONArray(); cities.add("New York"); cities.add("Bangalore"); cities.add("San Francisco"); obj.put("cities", cities); try < FileWriter file = new FileWriter("data.json"); file.write(obj.toJSONString()); file.flush(); file.close(); >catch (IOException e) < e.printStackTrace(); >System.out.print(obj.toJSONString()); > > 

Notice the @SuppressWarnings(«unchecked») annotation on main method? This was done to avoid warnings related to Type safety. JSONObject extends HashMap but doesn’t support Generics, so Eclipse IDE gives warning as below. Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap should be parameterized

json-simple example to read JSON from file

For reading JSON from file, we have to use org.json.simple.parser.JSONParser class. JSONParser parse method returns JSONObject. Then we can retrieve values by passing key names. Below is json-simple example to read JSON from file.

package com.journaldev.json.write; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JsonSimpleReader < public static void main(String[] args) throws ParseException, FileNotFoundException, IOException < JSONParser parser = new JSONParser(); Reader reader = new FileReader("data.json"); Object jsonObj = parser.parse(reader); JSONObject jsonObject = (JSONObject) jsonObj; String name = (String) jsonObject.get("name"); System.out.println("Name = " + name); long age = (Long) jsonObject.get("age"); System.out.println("Age = " + age); JSONArray cities = (JSONArray) jsonObject.get("cities"); @SuppressWarnings("unchecked") Iteratorit = cities.iterator(); while (it.hasNext()) < System.out.println("City = " + it.next()); >reader.close(); > > 
Name = Pankaj Kumar Age = 32 City = New York City = Bangalore City = San Francisco 

That’s all for a quick roundup of json-simple. However if you want to work with complex JSON data, you should use Jackson or Gson. You can also give JSR353 a try that got added into Java 7.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

How to work with JSON easily in Java

Carlos Delgado

Learn how to create and manipulate JSON strings in Java.

How to work with JSON easily in Java

JSON is a light-weight, language independent, data interchange format that is being used nowadays on every single web API available out there. If you are willing to manipulate this kind of data in a Java environment, we’ll explain you how to achieve it easily using the org.json package.

1. Include org.json package

Java by default doesn’t offer any integrated functionality to parse or create JSON unlike PHP or other languages, instead you will need to rely on a third party library/package. In this tutorial, we’ll use the org.json. The files in this package implement JSON encoders/decoders in Java. It also includes the capability to convert between JSON and XML, HTTP headers, Cookies, and CDL. This is a reference implementation. There is a large number of JSON packages in Java. Perhaps someday the Java community will standardize on one. Until then, we recommend you to use the org.json package that makes the things pretty easy.

You can either download the jar file of the package from the maven repository and include it manually in your project or if your project is maven based, you may edit the pom.xml file and add the dependency:

For more information about this package, please visit the official repository at Maven here. After including the library, you will be able to import the package with import org.json.*; in your code.

2. Using the library to manipulate JSON

As every tutorial in Our Code World, you will learn by doing and reading some examples. We’ll share with you a couple of the most used features when you work with JSON in Java:

A. Creating JSON objects

The put method of a JSONObject class allows you to define a new key with a value to the object:

package sandbox; import org.json.*; public class Sandbox < /** * Generating a JSON Object * * @param args */ public static void main(String[] args) < JSONObject myObject = new JSONObject(); // Basic strings myObject.put("name", "Carlos"); myObject.put("last_name", "Carlos"); // Primitive values myObject.put("age", new Integer(21)); myObject.put("bank_account_balance", new Double(20.2)); myObject.put("is_developer", new Boolean(true)); // Key with array double[] myList = ; myObject.put("number_list", myList); // Object inside object JSONObject subdata = new JSONObject(); myObject.put("extra_data", subdata); // Generate JSON String System.out.print(myObject); > > 

The code will print the following structure in the console of the generated JSON string:

< "number_list": [ 1.9, 2.9, 3.4, 3.5 ], "extra_data": <>, "name": "Carlos", "last_name": "Carlos", "bank_account_balance": 20.2, "age": 21, "is_developer": true >

B. Creating JSON Arrays

The put method of a JSONArray class allows you to push some value to the array:

package sandbox; import org.json.*; public class Sandbox < /** * Generating a JSON Array * * @param args */ public static void main(String[] args) < JSONArray myArray = new JSONArray(); // Push mixed values to the array myArray.put(1); myArray.put(2); myArray.put(3); myArray.put(4); myArray.put(new Boolean(true)); myArray.put(new Boolean(false)); myArray.put("Some String Value"); // Generate JSON String System.out.print(myArray); >> 

The code will print the following structure in the console of the generated JSON string:

[1,2,3,4,true,false,"Some String Value"]

C. Parsing JSON strings

If you are willing to convert a JSON string in your code (converting it to arrays or objects), just provide the string as first argument of the constructor of the class according to the type, for example, if you want to convert a string of JSONArray:

package sandbox; import org.json.*; public class Sandbox < /** * Parsing a JSONArray string * * @param args */ public static void main(String[] args) < JSONArray myJson = new JSONArray("[123,<\"1\":<\"2\":<\"3\":<\"4\":[5,<\"6\":7>]>>>>]"); // Print first value of the array System.out.print(myJson.get(0)); // Print second value of the array System.out.print(myJson.get(1)); > > 

Or if you want to convert a string to a JSONObject:

package sandbox; import org.json.*; public class Sandbox < /** * Parsing a JSONObject string * * @param args */ public static void main(String[] args) < JSONObject myJson = new JSONObject("< \"number_list\": [ 1.9, 2.9, 3.4, 3.5 ], \"extra_data\": <>, \"name\": \"Carlos\", \"last_name\": \"Carlos\", \"bank_account_balance\": 20.2, \"age\": 21, \"is_developer\": true >"); // Get some keys from the JSON Object System.out.print(myJson.get("name")); // Carlos System.out.print(myJson.get("age")); // 21 > > 

Источник

Оцените статью